Home / Programs / Constructor Chaining in Java
🚀 Programming Example

Constructor Chaining in Java

👁 27,273 Views
💻 Practical Program
📘 Step Learning
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.

💻 Program Code

 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.
 */

                        

🖥 Program Output

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

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.