Card 04/ 10
All 10 cards
WalkthroughDifficulty: Intermediate1 min
Tracing Three Constructors From new to the First Field
Three classes in a line, each printing as it goes, so the order is not something to believe but something to read off the output.
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() actually does
Step 1 of 5
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.
The useful consequence: a field assigned in a parent constructor is already set when the subclass body runs, so a subclass can overwrite it and a parent can never see the subclass's version.