Saturday, September 21

Method Overriding VS Method Hiding in java





                                  Method Overriding VS Method Hiding in java



If and instance  method in a subclass has same signature  and return type as instance method in the superclass ,it is called overriding.Method signature means name, and the number and the type of its parameters. Number ,type of the parameters should be same in method written in super class and sub class.

 overriding method can also return a subtype of the type returned by the super class method. This is called a co-variant return type.
Foe example

public class Animal {
  
    public void test() {
       
 }
}




public class Dog extends Animal {
   
    public void test() {
    }

}
test() method in Dog class is overridden .

If a  class method in subclass has the same signature as a class method in the superclass, This is called method hiding.

For example

public class Animal {
    public static void test() {
       ;
    }
  
}


public class Dog extends Animal {
    public static void test() {
      
    }
   }
here test() method in Dog class hides test() method of Animal superclass




In case of overriding method defined in subclass is invoked If object of subclass is created and assigned to a reference of superclass or subclass .i.e. if instance of Dog class is assigned to a reference of Dog class or animal class and test() method is invoked ,method written in Dog class will be invoked









 The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass. I.e. If reference is of Animal class animal class test() method would be invoked but if reference is of Dog class , Dog class test() method would be invoked.

Lets take another example :

public class Animal {
    public static void testClass() {
        System.out.println("Animal---> Class Method.");
    }
    public void testInstance() {
        System.out.println("Animal---> Instance method.");
    }
}



public class Dog extends Animal {
    public static void testClass() {
        System.out.println("Dog------> class metohd");
    }
    public void testInstance() {
        System.out.println("Dog---->Instance method.");
    }

    public static void main(String[] args) {
        Dog myCat = new Dog();
        Animal animal = lazyDog;
        Animal.testClassMethod();
        animal.testInstanceMethod();
    }
}

The Dog class overrides the instance method in Animal and hides the class method in Animal. The main method in this class creates an instance of Dog and calls testClass() on the class and testInstance() on the instance.

The output from this program is as follows:

Animal---> Class Method
Dog---->Instance method.






Conclusion
So class method invocation depends upon the reference type while instance method invocation depends upon the type of instance created. Method hiding happens for static methods and method overriding for instance methods


-->

2 comments: