Constructor Chaining: The Initialization Sequence
What you'll learn: How constructors execute in a strict top-down order through the inheritance hierarchy, always initializing superclasses before subclasses.
When you create an object from a subclass, Java doesn't just call that one constructor—it triggers a chain reaction that starts at the very top of the hierarchy and works its way down.
The Execution Flow
Here's what happens when you instantiate a subclass:
- Superclass constructor executes first (triggered by
super()) - Then the subclass constructor body runs
If your superclass also extends another class, its superclass constructor runs first, and so on, all the way up to Object. Think of it like building a house: you must pour the foundation before framing the walls, and frame the walls before adding the roof.
Why This Order Matters
The subclass depends on its superclass being fully initialized. If the subclass constructor ran first, it might try to use superclass fields or methods that aren't ready yet—a recipe for disaster.
The Chain in Action
class Animal {
Animal() {
System.out.println("Animal constructor");
}
}
class Dog extends Animal {
Dog() {
// Implicit super() called here first
System.out.println("Dog constructor");
}
}
class Beagle extends Dog {
Beagle() {
// Implicit super() called here first
System.out.println("Beagle constructor");
}
}
// Creating: new Beagle()
// Output:
// Animal constructor
// Dog constructor
// Beagle constructor
The execution flows from Animal → Dog → Beagle, even though you only called new Beagle().
Key Takeaway: Constructor chaining ensures superclass constructors execute before subclass constructors, guaranteeing that every object is built from the foundation upward through the entire inheritance hierarchy.