Card 03/ 10

ConceptDifficulty: Intermediate1 min

Constructor Chaining: Parent Constructors Finish First

A subclass sets a field, and the parent's value for it was already there before the subclass line ran.

One new runs a constructor from every class in the hierarchy. Each constructor first calls its parent's, so the calls go up to Object, and the bodies then complete from the most general class down to the most specific. A subclass body therefore always runs after its parent's.

The symptom this explains: a field set in both a parent and a subclass constructor ends up with the subclass's value, and a parent constructor that reads a subclass field sees it empty. Two constructors, both setting tier:

java
class Customer {
    String tier;
    Customer() { tier = "standard"; }
}

class PremiumCustomer extends Customer {
    PremiumCustomer() { tier = "premium"; }
}
Constructors begin at the subclass and complete from the top down

Entering goes down the diagram and completing comes back up it, so the most general class finishes first and the most specific finishes last. tier is set to "standard" and then to "premium", in that order, and the subclass wins because it goes last.

That order is the reason a subclass can rely on the parent's fields already being set, and the reason a parent constructor must never call a method the subclass overrides: the subclass's own fields are still empty when it runs.

The walkthrough that follows traces the same order through three classes, with each constructor printing a line so the sequence can be read straight off the output.