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.
This article is contributed by Twinkle Tyagi .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Accessing Grandparent’s member in Java using super
- Two interfaces with same methods having same signature but different return types
- Private Constructors and Singleton Classes in Java
- Understanding Classes and Objects in Java
- Classes and Objects in Java
- Access specifiers for classes or interfaces in Java
- Abstract Classes in Java
- Primitive Wrapper Classes are Immutable in Java
- Wrapper Classes in Java
- Nested Classes in Java
- Why Java Interfaces Cannot Have Constructor But Abstract Classes Can Have?
- Creating an Server-Client Application using the DatagramPacket and DatagramSocket classes
- Messages, aggregation and abstract classes in OOPS
- Utility methods of Wrapper classes | valueOf(), xxxValue(), parseXxx(), toString()
- Primitive data type vs. Object data type in Java with Examples
- Arithmetic Expression Having Only + and * Operators in Java
- Can We Define a Method Name Same as Class Name in Java?
- Comparison of boolean data type in C++ and Java
- Static and Dynamic data structures in Java with Examples
- Parallel Data Processing in Java | Set 1