Can we call Superclass’s static method from subclass in Java?

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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.

 Live Demo

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 −

 Live Demo

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
raja
Published on 02-Jul-2019 11:55:31
Advertisements