Card 04/ 10
Constructor Order Walkthrough: Tracing new IsaAccount()
Three classes in a line, each printing as it goes, so the order can be read off the output.
Following one new through three classes shows constructor order directly: memory is allocated, each constructor hands on to its parent, and the bodies print from the top of the hierarchy down. You need three classes that extend one another, each printing from its constructor:
class Account {
Account() { System.out.println("Account body"); }
}
class SavingsAccount extends Account {
SavingsAccount() { System.out.println("Savings body"); }
}
class IsaAccount extends SavingsAccount {
IsaAccount() { System.out.println("Isa body"); }
}What one new IsaAccount() does
Memory is allocated for the whole object
Every field from every class in the chain is laid out at once, and each is set to its type's default: zero, false or null. Nothing you wrote has run yet, and the object already exists in memory.
IsaAccount's constructor is entered, and immediately defers
Its first statement is a call to the parent constructor. You did not write one, so the compiler inserted super(); as the first line. Nothing in the IsaAccount body has run.
SavingsAccount defers in the same way, and so does Account
Each one enters and hands straight on upwards. The chain ends at Object, which every class extends whether or not anybody wrote it down.
Bodies complete from the top back down
Account body
Savings body
Isa bodyObject finishes first and silently. Then each body runs in turn on the way back down, which is why the most general class prints first even though the most specific one was entered first.
The reference is handed back
Only now does new produce the address. Every constructor in the chain has completed, which is the guarantee that makes it safe to use the object at all.
You know the trace is right when the output reads Account body, Savings body, Isa body: most general first. The useful consequence is that a field assigned in a parent constructor is already set when the subclass body runs, so a subclass can overwrite it, and the parent constructor never sees the subclass's value, because the subclass body has not run yet.
← → move through sections and cards