Card 08/ 09
All 9 cards
ExerciseDifficulty: Advanced1 min
Four Calls: Write Down Which Body Runs
One hierarchy, four call sites. For each, decide what is printed or whether it fails to compile. Write all four down before opening the reveal.
class Base {
String kind = "base";
String name() { return "Base"; }
static String origin() { return "Base.origin"; }
String only() { return "base only"; }
}
class Sub extends Base {
String kind = "sub";
@Override String name() { return "Sub"; }
static String origin() { return "Sub.origin"; }
String extra() { return "sub extra"; }
}
Base b = new Sub();System.out.println(b.name());
System.out.println(b.kind);
System.out.println(b.origin());
System.out.println(b.extra());What each of the four lines does
| Line | Result | Decided by |
|---|---|---|
b.name() | Sub | The runtime class of the object — an overridden method |
b.kind | base | The declared type of b — fields are hidden, not overridden |
b.origin() | Base.origin | The declared type — static methods are hidden too, and are not polymorphic |
b.extra() | Does not compile | Base makes no such promise, whatever the object is |
Only the first line consults the object. The other three are all answered from the declared type, which is the reason the third line is a warning in most tools: calling a static method through a reference reads as though the object chose it.