The super() Call Must Be First
You'll learn: Why Java enforces that super() or this() must appear as the very first statement in any constructor body.
Why the First Statement Rule Exists
When you explicitly call super() (or this() to chain to another constructor in the same class), Java requires it to be the first executable statement in your constructor body. No other code can come before it—not even a simple variable assignment or print statement.
The Reasoning Behind This Rule
Java enforces this rule to guarantee that every object is fully initialized from the top down. The superclass must be constructed before the subclass can safely use inherited fields or methods. If you could run arbitrary code before calling super(), you might accidentally try to access superclass members that don't exist yet—leading to unpredictable behavior or crashes.
Think of it like building a house: you must pour the foundation (superclass) before framing the walls (subclass). You can't start hammering walls while the foundation is still being mixed!
What This Looks Like in Code
class Animal {
String name;
Animal(String name) {
this.name = name;
}
}
class Dog extends Animal {
String breed;
Dog(String name, String breed) {
// super(name) MUST come first
super(name); // ✓ Correct
this.breed = breed; // Now safe to initialize subclass fields
}
}
What Happens if You Break the Rule
Dog(String name, String breed) {
this.breed = breed; // ✗ Compile error!
super(name); // Cannot call super() after other code
}
Java will refuse to compile this code.
Key Takeaway: The super() or this() call must be the first statement in a constructor to ensure proper top-down initialization of the inheritance hierarchy.