Card 08/ 09

ExerciseDifficulty: Advanced1 min

Practice: Which Method Body or Field Each Call Uses

An override, a hidden field, a hidden static method and a missing method, on one variable.

Only an overridden instance method is chosen by the object; fields and static methods are resolved from the declared type, and the declared type decides what may be called at all. Using that, decide what each of the four lines prints, or that it does not compile, all four before opening the answer.

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.