Sunday 8 May 2016

Reference variable of parent class can access the overridden method in child class.

Hi,
As we know that the reference variable of parent class storing the object of child class can only access the members of its own class(i.e. the parent class). But you should keep in mind that it can access the overridden method in the child class.

The famous example is given here on oracle docs : - click here

I'm pasting that code snippet here also : -
public class Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Animal");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Animal");
    }
}
//The second class, a subclass of Animal, is called Cat:

public class Cat extends Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Cat");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Cat");
    }

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

The output is : 


The static method in Animal
The instance method in Cat

This proves.

No comments:

Post a Comment