Constructor Chaining in Java

Java Programming Language / Class, Object and Methods in java

27210

Program:

 class Democlass{
   int  value1;
   int  value2;
    Democlass(){
      value1 = 1;
      value2 = 2;
      System.out.println("Inside 1st Parent Constructor");
   }
   Democlass(int a){
      value1 = a;
      System.out.println("Inside 2nd Parent Constructor");
   }
  public void display(){
     System.out.println("Value1 === "+value1);
     System.out.println("Value2 === "+value2);
  }
  public static void main(String args[]){
     DemoChild d1 = new DemoChild();
     d1.display();
  }
}
class DemoChild extends Democlass{
    int value3;
    int value4;
    DemoChild(){
    value3 = 3;
    value4 = 4;
    System.out.println("Inside the Constructor of Child");
    }
    public void display(){
      System.out.println("Value1 === "+value1);
      System.out.println("Value2 === "+value2);
      System.out.println("Value1 === "+value3);
      System.out.println("Value2 === "+value4);
   }
}

/*
Consider a  scenario where a base class is extended by a child .
Whenever an object of the child class is created , the constructor
 of the parent class is invoked first.This is called Constructor chaining.
 */

Output:

Inside 1st Parent Constructor
Inside the Constructor of Child
Value1 === 1
Value2 === 2
Value1 === 3
Value2 === 4
Press any key to continue . . .

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.