Card 04/ 09

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.

java
Customer c = new PremiumCustomer();

c.label();          // runs PremiumCustomer's body
c.discountRate();   // will not compile

Two different questions are being answered by two different parts of the system, at two different times.

Which part of the system answers which question
QuestionAnswered byUsingWhen
May this method be called here?The compilerThe declared type of the variableAt compile time
Which body actually runs?The virtual machineThe runtime class of the objectWhile 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.