Method Hiding in Java

Method Hiding in Java Definition -

Redefining super class static method in subclass is called method hiding. In the below given example static method m1() is available in both A and B class i.e called method Hiding.

//A.java

 class A {
       static void m1() {
       System.out.println(" class A static method "); 
      }
      void m2() {
        System.out.println("class A non-static method");
     }
}

    

//B.java

class B extends A {
      static void m1() {
             System.out.println(" class B m1 method");
       }
       void m2() {
            System.out.println(" class B m2 method");
       }
 }

//Test.java

class Test {
       public static void main(String[] args) {
       A a = new B();
       a.m1();
       a.m2();
     }
 }

Output -

class A static method 
class B m2 method

Static and non-static method execution -

  • Static method executed from reference variable type class.
  • non-static method executed from current reference variable pointing object class.
  • current reference variable means the reference variable using which we are calling a method. 
  • B b = new B(); In this case B is a reference variable and B() is current object, in this case both static and non-static method executed from B class because reference variable type and object type both are same.
  • A a = new B();  In this case static method executed from A class, non-static method executed from B class.

 

Leave a Comment

%d bloggers like this: