12 May 2015

Method Hiding in Java with Example

If we try to override a static method then the method in the sub class hides the super class method (where as in case of instance method the method in the sub class overrides the super class method). This is called as Method Hiding in java.

As the method is actually hidden instead of overridden so both super class & sub class method is available to access and it depends on from where it is invoked whether from super class or sub class.

Let's observe its behavior with an example.
class A{
   public static void display(){
      System.out.println("Inside A");
   }
}
class B extends A{
   public static void display(){
      System.out.println("Inside B");
   } 
}
public class Test{
   public static void main(String args[]){
      B obj1 = new B();
      obj1.display();   // Output: Inside B
      A obj2 = new B();
      obj2.display();   // Output: Inside A
   }
}
On observing the above two outputs it is clear that based on the type of reference (class A or class B) the respective static method is being invoked. And, the second output concludes that static method of class A is still available i.e., the static method got hidden instead of overridden.

Note: Calling static methods on instances rather than classes is a very bad practice, and should never be done.





Popular Posts

Write to Us
Name
Email
Message