The reference variable of the Parent class can store its object reference and its child object references. In Java, methods are virtual by default (see here for details). What about non-method members? For example, predict the output of the following Java program.
JAVA
// A Java program to demonstrate that non-method // members are accessed according to reference // type (Unlike methods which are accessed according // to the referred object) class Parent { int value = 1000; Parent() { System.out.println("Parent Constructor"); } } class Child extends Parent { int value = 10; Child() { System.out.println("Child Constructor"); } } // Driver class class Test { public static void main(String[] args) { Child obj=new Child(); System.out.println("Reference of Child Type :" + obj.value); // Note that doing "Parent par = new Child()" // would produce same result Parent par = obj; // Par holding obj will access the value // variable of parent class System.out.println("Reference of Parent Type : " + par.value); } }
Output:
Parent Constructor Child Constructor Reference of Child Type : 10 Reference of Parent Type : 1000
If a parent reference variable holds a reference to a subclass, and we have a "value" variable in both the parent class and the subclass, it will refer to the parent class "value" variable, regardless of whether it holds a subclass object reference. A reference holding a subclass object reference will not be able to access the members (functions or variables) of the subclass. This is because the parent reference variable can only access the fields in the parent class. Therefore, the type of the reference variable determines which version of the "value" will be called, not the type of object being instantiated. This is because the compiler only uses a special runtime polymorphism mechanism for methods. (The type of object being instantiated determines which version of the method to call)
It is possible to access child data members using the parent directory with broadcast type.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.