Do you know what is method hiding ?

Method hiding is possible with static method.

Let's see example:

class A{
 static void show(){
   System.out.println("From A class");
   }
  }
  public class B extends A{
  static void show(){
   System.out.println("From B class");
   }
   public static void main(String []args){
        A a =new HelloWorld();
        B b =new B();
        a.show(); // A class show method will call
        b.show(); // B class show method will call
      }
 }




 Here with A class object reference  "a" can't see the B class show method.

So B class show method is not visible to A class reference.

Note:   Accessing Static members with instance of a class not a best practice.

Why? - Because for static members memory will allocate at the time class loading so we can access this with class name.


Is it Overriding?

NO -  This is not Overriding but it is valid.


No comments:

Post a Comment