Initialization Order with Constructor Chaining
You'll learn: How fields and initializer blocks execute only once, even when constructors chain to each other with this().
When you chain constructors using this(), you might wonder: "Do my fields and initializer blocks run multiple times?" The answer is no—they execute exactly once, before the first constructor body runs.
How It Works
Think of initialization like building a house: you pour the foundation (fields and initializer blocks) exactly once, then you might add rooms in stages (constructor chaining). You don't pour a new foundation for each room!
Here's the sequence when you create an object with chained constructors:
- Fields are initialized with their declared values
- Instance initializer blocks execute in order
- The first constructor in the chain (the one called by
this()) begins executing - Control flows through each constructor body in turn
- The original constructor you called completes last
Key Point
Even if Constructor B calls Constructor A with this(), the fields and initializer blocks don't run again when Constructor A starts—they already ran before Constructor B began.
public class Example {
private int x = 10; // Step 1: field initialized
{ x += 5; } // Step 2: initializer block runs
public Example() { // Step 3: first in chain executes
x += 100; // x is now 115
}
public Example(int bonus) { // Step 4: calling constructor
this(); // calls other constructor
x += bonus; // x becomes 115 + bonus
}
}
When you call new Example(20), fields and blocks run once, then both constructor bodies execute in sequence.
Key Takeaway: Fields and initializer blocks execute exactly once per object creation, before any constructor body runs—even with constructor chaining.