Card 04/ 09
All 9 cards
ConceptDifficulty: Intermediate1 min
The Compiler Checks the Reference; the JVM Picks the Object
A method call that runs the subclass's body will not compile if you add a second call to a method only the subclass has. Both calls are on the same variable, pointing at the same object.
Customer c = new PremiumCustomer();
c.label(); // runs PremiumCustomer's body
c.discountRate(); // will not compileTwo different questions are being answered by two different parts of the system, at two different times.
| Question | Answered by | Using | When |
|---|---|---|---|
| May this method be called here? | The compiler | The declared type of the variable | At compile time |
| Which body actually runs? | The virtual machine | The runtime class of the object | While running |
So the declared type is a contract about what you may ask for, and the object decides how the asking is answered. c.discountRate() fails because Customer makes no such promise, regardless of what c happens to be holding today.
That split is why declaring variables by the widest useful type costs nothing at runtime and buys everything at compile time: you keep every body the object has, and you give up only the ability to ask for things the contract does not include.