Why can't we use the "super" keyword is in a static method in java?


A static method or, block belongs to the class and these will be loaded into the memory along with the class. You can invoke static methods without creating an object. (using the class name as reference).

Where, the "super" keyword in Java is used as a reference to the object of the super class. This implies that to use "super" the method should be invoked by an object, which static methods are not.

Therefore, you cannot use "super" keyword from a static method.

Example

In the following Java program the class ThisExample contains a private variable name with setter and getter methods and an instance method display(). From the main method (which is static) we are trying to invoke the display() method using the this keyword.

class SuperClass{
   protected String name;
}
public class SubClass extends SuperClass {
   private String name;
   public static void setName(String name) {
      super.name = name;
   }
   public void display() {
      System.out.println("name: "+super.name);
   }
   public static void main(String args[]) {
      new SubClass().display();
   }
}

Compile time error

SubClass.java:7: error: non-static variable super cannot be referenced from a static context
   super.name = name;
   ^
1 error
raja
Published on 05-Aug-2019 12:32:45
Advertisements