Parent and Child classes having same data member in Java

Course Curriculum

Parent and Child classes having same data member in Java

Parent and Child classes having same data member in Java

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.

// 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 num = 2000;
Parent()
{
System.out.println("Parent Constructor");
}
}

class Child extends Parent
{
int num = 20;
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.num);

// 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.num);
}
}
Output:

Parent Constructor
Child Constructor
Reference of Child Type : 20
Reference of Parent Type : 2000

Using final with Inheritance in Java (Prev Lesson)
(Next Lesson) Object Serialization with Inheritance in Java
', { 'anonymize_ip': true });