Card 04/ 09

ConceptDifficulty: Intermediate1 min

Declared Type vs Runtime Type

Two calls on the same variable and the same object: one runs the subclass body, the other will not compile.

A variable's declared type is the type written in its declaration; the runtime type is the class of the object it holds. The compiler uses the declared type to decide which methods may be called. The JVM uses the runtime type to decide which body runs.

A method call that runs the subclass's body sits next to a call to a method only the subclass has, and the second will not compile. 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
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.