Card 05/ 09

GotchaDifficulty: Intermediate1 min

Why a Field Does Not Override the Way a Method Does

A subclass declares a field with the same name as its parent's and gives it a different value. The method prints the subclass's value and the direct read prints the parent's, from the same object on the same line.

java
class Animal {
    String name = "animal";
    String describe() { return name; }
}
class Dog extends Animal {
    String name = "dog";
    @Override String describe() { return name; }
}

Animal a = new Dog();
System.out.println(a.name + " " + a.describe());
text
animal dog

There are two name fields in that object, not one. A subclass field with the same name hides the parent's rather than replacing it, and both are still there.

Which one a read finds is decided by the declared type of the expression, at compile time — a is declared Animal, so a.name is the parent's. Methods are the other way round, which is why a.describe() runs Dog's body and that body sees Dog's field.

Do not reuse a parent's field name. If a subclass needs a different value in the same conceptual slot, set the inherited field in the constructor, or read it through a method the subclass can override.