Card 08/ 09

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.

java
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();
java
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
Each call, its result, and what decided it
LineResultDecided by
b.name()SubThe runtime class of the object — an overridden method
b.kindbaseThe declared type of b — fields are hidden, not overridden
b.origin()Base.originThe declared type — static methods are hidden too, and are not polymorphic
b.extra()Does not compileBase 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.