Card 08/ 09
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.
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.
← → move through sections and cards