The Subclass Constructor and Implicit super()
What you'll learn: How Java automatically initializes the superclass portion of every subclass object.
When you create a subclass, you're building on top of an existing class. That means every object of your subclass contains all the fields and behavior of its parent class—the superclass. But who initializes those inherited parts?
The Invisible First Line
Every subclass constructor automatically calls super() as its very first action—even if you don't write it explicitly. This ensures the superclass is properly initialized before the subclass adds its own customizations.
Think of it like building a house: before you can add a second floor (subclass), you must first construct the ground floor (superclass). Java enforces this by inserting an invisible super() call at the beginning of every subclass constructor.
How It Works
class Animal {
Animal() {
// Superclass constructor
}
}
class Dog extends Animal {
Dog() {
// Java automatically inserts: super();
// Your subclass initialization follows
}
}
When you write new Dog(), Java:
- Calls the
Dogconstructor - Immediately calls
super()to initialize theAnimalportion - Then executes the rest of the
Dogconstructor body
You won't see the super() call in your code, but it's always there, working behind the scenes to ensure proper object construction from the ground up.
Why This Matters
Without this automatic initialization, inherited fields would remain uninitialized, leading to broken objects. Java's implicit super() guarantees that every part of your object hierarchy is properly constructed, layer by layer.
Key Takeaway: Every subclass constructor implicitly calls super() first to initialize the inherited superclass fields and execute superclass initialization logic—even when you don't write it yourself.