Order of Constructor and Initialization Block Execution in Java
When a class hierarchy is involved, the execution order of constructors and initialization blocks follows a top-down approach.
Order of Execution:
- Static Blocks (from parent to child)
- Instance Initialization Blocks (from parent to child)
- Constructors (from parent to child)
Step-by-Step Execution Order
Step | Element | Executed From |
---|---|---|
1️⃣ | Static Blocks | Parent → Child |
2️⃣ | Instance Initialization Blocks | Parent → Child |
3️⃣ | Constructor Execution | Parent → Child |
Example to Demonstrate Execution Order
class Parent {
// Static block
static {
System.out.println("Parent Static Block");
}
// Instance initialization block
{
System.out.println("Parent Instance Block");
}
// Constructor
Parent() {
System.out.println("Parent Constructor");
}
}
class Child extends Parent {
// Static block
static {
System.out.println("Child Static Block");
}
// Instance initialization block
{
System.out.println("Child Instance Block");
}
// Constructor
Child() {
System.out.println("Child Constructor");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Creating First Child Object...");
Child c1 = new Child();
System.out.println("\nCreating Second Child Object...");
Child c2 = new Child();
}
}
Expected Output
Parent Static Block
Child Static Block
Creating First Child Object...
Parent Instance Block
Parent Constructor
Child Instance Block
Child Constructor
Creating Second Child Object...
Parent Instance Block
Parent Constructor
Child Instance Block
Child Constructor
Analysis of Execution Order
First Object Creation (new Child()
)
1️⃣ Static Blocks (Executed Only Once)
Parent Static Block
Child Static Block
2️⃣ Parent’s Instance Block
Parent Instance Block
3️⃣ Parent’s Constructor
Parent Constructor
4️⃣ Child’s Instance Block
Child Instance Block
5️⃣ Child’s Constructor
Child Constructor
Second Object Creation (new Child()
)
1️⃣ Static blocks are NOT executed again (they run only once per class). 2️⃣ Parent’s Instance Block → Parent Instance Block
3️⃣ Parent’s Constructor → Parent Constructor
4️⃣ Child’s Instance Block → Child Instance Block
5️⃣ Child’s Constructor → Child Constructor
Key Takeaways
1️⃣ Static blocks execute only once per class, when the class is loaded (top-down in hierarchy).
2️⃣ Instance blocks execute every time an object is created, before the constructor (top-down in hierarchy).
3️⃣ Constructors execute after all instance blocks (top-down in hierarchy).