๐ WAYPOINT LESSON
Constructor chains
โญโญ intermediateโณ 12 min read๐ Lesson 118 of 256
super first, implicit super(), protected visibility, top-down state build.
Constructors are the exception to dispatch-on-object: they run top-down โ superclass body first, then down the chain:
public class Pet {
protected String name;
public Pet(String name) { this.name = name; }
}
public class Cat extends Pet {
private int lives;
public Cat(String name, int lives) {
super(name); // MUST be first statement
this.lives = lives;
}
}
Rules the exam tests:
- If the subclass constructor calls
super(...), it must be the first statement. - If it does not call super at all, Java inserts
super()โ the parent's NO-ARG constructor. When the parent has only a String-arg constructor, that insertion is a compile error: "constructor Pet in class Pet cannot be applied to given types". protectedfields are visible to subclasses (and the same package) โprivateones are not, which is why Cat goes throughsuper(name)instead of touchingnamedirectly.
The chain order explains tracing questions: new Cat("M", 9) runs
Pet's body (name = "M"), then Cat's body (lives = 9). State builds
from the top of the hierarchy down.
โก Now practice
Ready to CodeInheritance labDispatch counts, constructor chains, missing-super repair, field shadowing.
5 challenges ยท ยท ~55 min