Parent and Child classes having same data member in Java

Java 8Server Side ProgrammingProgramming

The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.

Example

Following is an example −

 Live Demo

class Demo_base {
   int value = 1000;
   Demo_base() {
      System.out.println("This is the base class constructor");
   }
}
class Demo_inherits extends Demo_base {
   int value = 10;
   Demo_inherits() {
      System.out.println("This is the inherited class constructor");
   }
}
public class Demo {
   public static void main(String[] args) {
      Demo_inherits my_inherited_obj = new Demo_inherits();
      System.out.println("In the main class, inherited class object has been created");
      System.out.println("Reference of inherited class type :" + my_inherited_obj.value);
      Demo_base my_obj = my_inherited_obj;
      System.out.println("In the main class, parent class object has been created");
      System.out.println("Reference of base class type : " + my_obj.value);
   }
}

Output

This is the base class constructor
This is the inherited class constructor
In the main class, inherited class object has been created
Reference of inherited class type :10
In the main class, parent class object has been created
Reference of base class type : 1000

Explanation

A class named ‘Demo_base’ contains an integer value and a constructor that prints relevant message. Another class named ‘Demo_inherits’ becomes the child class to parent class ‘Demo_base’. This means, the ‘Demo_inherits’ class extends to the base class ‘Demo_base’.

In this class, another value for the same variable is defined, and a constructor of the child class is defined with relevant message to be printed on the screen. A class named Demo contains the main function, where an instance of the child class is created, and its associated integer value is printed on the screen. A similar process is done for the parent class, by creating an instance and accessing its associated value and printing it on the screen.

raja
Published on 14-Sep-2020 12:46:11
Advertisements