The reference variable of the Parent class is capable to hold its object reference as well as its child object reference.
In Java, methods are virtual by default (See this for details).
What about non-method members. For example, predict the output of following Java program.
Parent Constructor Child Constructor Reference of Child Type : 10 Reference of Parent Type : 1000
If a parent reference variable is holding the reference of the child class and we have the “value” variable in both the parent and child class, it will refer to the parent class “value” variable, whether it is holding child class object reference. The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. It is because compiler uses special run-time polymorphism mechanism only for methods.
It is possible to access child data members using parent pointer with typecasting. Please see last example of this for complete code.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.