Sahil Kapoor wrote:
The above code prints Animal, Dont you think it should print Dog.
Basically, while the Dog class inherits the Animal class' method. It is still a method of the Animal class -- meaning the code doesn't change. The Dog class simply calls the method of the Animal class, it doesn't get a copy of it.
Instance variable do not support polymorphism. So, the method of the Animal class will determine how to access instance variables at compile time. And at compile time, while compiling the Animal class, it is determined that you are accessing the variable of the Animal class.
If I understood you right, you are kinda getting confused with the term 'Inheritance'. If you look at the term 'Inheritance' and its features of an OOP language, yes it facitates a sub/child class to have access to the mebers of a super/parent class. Remember: It is to the immediate or direct parent class only and NOT any of them up in the hierarchy.
If still you want to a way, you can follow the other bartenders suggestion by typecasting the reference variable to that of the parent class which you are interested in!
// as the JVM checks for compatibility at the compile time only
// a superclass reference can only access its own instance variables , as it does not know anything about the instance variables of its subclasses ... i mean they aren't defined to him .. compile time polymorphism
// but a superclass reference uses the methods of the subclass it is referring to (obviosly if they are overridden) using the runtime polymorphism
// remember that the instace variables do not take part in run time polymorphism