Card 04/ 09
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:
Customer c = new PremiumCustomer();
c.label(); // runs PremiumCustomer's body
c.discountRate(); // will not compile| 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.
← → move through sections and cards