Shadowing of static methods in Java

Java 8Object Oriented ProgrammingProgramming

When superclass and the subclass contain the same instance methods including parameters, when called, the superclass method is overridden by the method of the subclass.

Example

 Live Demo

class Super{
   public void sample(){
      System.out.println("Method of the Super class");
   }
}
public class MethodOverriding extends Super {
   public void sample(){
      System.out.println("Method of the Sub class");
   }
   public static void main(String args[]){
      MethodOverriding obj = new MethodOverriding();
      obj.sample();
   }
}

Output

Method of the Sub class

Method shadowing

When superclass and subclass contain the same method including parameters and if they are static. The method in the superclass will be hidden by the one that is in the subclass. This mechanism is known as method shadowing.

Example

 Live Demo

class Super{
   public static void demo() {
      System.out.println("This is the main method of the superclass");
   }
}
class Sub extends Super{
   public static void demo() {
      System.out.println("This is the main method of the subclass");
   }
}
public class MethodHiding{
   public static void main(String args[]) {
      MethodHiding obj = new MethodHiding();
      Sub.demo();
   }
}

Output

This is the main method of the subclass

Reason

The key in method overloading is, if the superclass and subclass have a method with the same signature, to the object of the subclass both of them are available. Based on the object type (reference) you used to hold the object, the respective method will be executed.

SuperClass obj1 = (Super) new SubClass();
obj1.demo() // invokes the demo method of the super class
SubClass obj2 = new SubClass ();
obj2.demo() //invokes the demo method of the sub class

But, in case of static methods, since they don’t belong to any instance, you need to access them using the class name.

SuperClass.demo();
SubClass.Demo();

Therefore, if a superclass and subclass have static methods with the same signature, though a copy of the superclass method is available to the subclass object. Since they are static the method calls resolved at the compile time itself, overriding is not possible with static methods.

But, since a copy of the static method is available, if you call the subclass method the method of the superclass will be redefined/hidden.

raja
Published on 06-Sep-2019 12:12:02
Advertisements