Constructor Chaining in Java: Implicit and Explicit Calls Explained

Constructor Chaining in Java

Constructor chaining is a mechanism in Java where one constructor calls another constructor, usually from the parent (super) class, during object creation.
 
This process ensures that all parent class constructors are executed before child class constructors, maintaining proper object initialization.

Key Requirements

Constructor chaining requires inheritance
It is performed using the super() statement
It cannot be performed within the same class using super()
The super() call must be the first statement in the constructor

🌍 Real-Life Example

Building Construction
First, foundation is built (Parent class constructor)
Then walls and rooms are built (Child class constructor)
Similarly, Java first executes the superclass constructor, then the subclass constructor.

🔹 Types of Constructor Chaining

Constructor chaining can be performed in two ways:
Implicit Constructor Call
Explicit Constructor Call

1. Implicit Constructor Call

Definition

An implicit constructor call is automatically performed by the Java compiler when the programmer does not explicitly call a superclass constructor.
Compiler automatically inserts super()
Only the default or zero-parameter constructor of the superclass is called
Parameterized constructors are not called implicitly
🧠 Example
class Parent {
    Parent() {
        System.out.println("Parent Constructor");
    }
}
class Child extends Parent {
    Child() {
        System.out.println("Child Constructor");
    }
}

public class Main {
    public static void main(String[] args) {
        Child c = new Child();
    }
}
🔍 Output
Parent Constructor
Child Constructor

2. Explicit Constructor Call
✅ Definition

An explicit constructor call is performed by the programmer using the super() statement inside the constructor body.
Can call default, zero-parameter, or parameterized constructors
Must be the first statement in the constructor
🧠 Example
class Parent {
    Parent(int x) {
        System.out.println("Parent Parameterized Constructor: " + x);
    }
}
class Child extends Parent {
    Child() {
        super(10);
        System.out.println("Child Constructor");
    }
}
public class Main {
    public static void main(String[] args) {
        Child c = new Child();
    }
}
🔍 Output
Parent Parameterized Constructor: 10
Child Constructor

📌 Important Points to Remember

  • super() must be the first statement in a constructor
  • If no super() is written, compiler inserts it automatically
  • Constructor chaining ensures proper initialization order
  • Only one constructor can be called from another constructor

Comments

Popular posts from this blog

History of Java Programming Language | Features, Origin & Uses

Inheritance in Java: Types, Examples, and Explanation

Java Programming Features Every Beginner Should Know