Card 03/ 10
All 10 cards
ConceptDifficulty: Intermediate1 min
The Constructor Chain Runs Upwards and Finishes Downwards
A subclass constructor sets a field to a value, and by the time the object is handed back the field holds something else. Nothing between the two assignments looks like it touches that field.
One new runs every constructor up the hierarchy, and the order is fixed. Before a subclass constructor executes a single line of its own body, the parent's constructor has already run to completion.
class Customer {
String tier;
Customer() { tier = "standard"; }
}
class PremiumCustomer extends Customer {
PremiumCustomer() { tier = "premium"; }
}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.