Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we call Superclass’s static method from subclass in Java?
A static method is the one which you can call without instantiating the class. If you want to call a static method of the superclass, you can call it directly using the class name.
Example
public class Sample{
public static void display(){
System.out.println("This is the static method........");
}
public static void main(String args[]){
Sample.display();
}
}
Output
This is the static method........
It also works, if you call a static method using an instance. But, it is not recommended.
public class Sample{
public static void display(){
System.out.println("This is the static method........");
}
public static void main(String args[]){
new Sample().display();
}
}
Output
This is the static method........
If you compile the above program in eclipse you will get a warning as −
Warning
The static method display() from the type Sample should be accessed in a static way
Calling the static method of the superclass
You can call the static method of the superclass −
- Using the constructor of the superclass.
new SuperClass().display();
- Directly, using the name of the superclass.
SuperClass.display();
- Directly, using the name of the subclass.
SubClass.display();
Example
Following Java example calls the static method of the superclass in all the 3 possible ways −
class SuperClass{
public static void display() {
System.out.println("This is a static method of the superclass");
}
}
public class SubClass extends SuperClass{
public static void main(String args[]){
//Calling static method of the superclass
new SuperClass().display(); //superclass constructor
SuperClass.display(); //superclass name
SubClass.display(); //subclass name
}
}
Output
This is a static method of the superclass This is a static method of the superclass This is a static method of the superclass
Advertisements