In C++ we have all class member methods as non-virtual. In order to make so, we have to use a keyword as a prefix known as virtual. Whereas in Java, we have all class member methods as virtual by default. In order to make them non-virtual, we use the keyword final.
Reference variables in Java are basically variables holding the address of the object in hexadecimal type which later is converted to the binary system that basically is the address of the object to be stored on the heap memory.
Reference variables that differ from primitive types as their size can not be calculated. In Java, the reference variable of the Parent class is capable to hold its object reference as well as its child object reference. Let’s see about non-method members with the help of an example.
Example:
Java
class Parent {
int value = 1000 ;
Parent()
{
System.out.println( "Parent Constructor" );
}
}
class Child extends Parent {
int value = 10 ;
Child()
{
System.out.println( "Child Constructor" );
}
}
class GFG {
public static void main(String[] args)
{
Child obj = new Child();
System.out.println( "Reference of Child Type :"
+ obj.value);
Parent par = obj;
System.out.println( "Reference of Parent Type : "
+ par.value);
}
}
|
OutputParent Constructor
Child Constructor
Reference of Child Type :10
Reference of Parent Type : 1000
Output Explanation: 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. This is because the parent reference variable can only access fields that are in the parent class. Thus the type of reference variable decides which version of “value” will be called and not the type of object being instantiated. It is because the compiler uses a special run-time polymorphism mechanism only for methods. (There the type of object being instantiated decides which version of the method to be called).
Note: It is made possible to access child data members using parent pointer with typecasting.
This article is contributed by Twinkle Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.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.