Card 05/ 09

GotchaDifficulty: Intermediate1 min

Field Hiding: Why Fields Do Not Override Like Methods

The same object, the same line, and two different names printed.

A subclass field with the same name as a parent field does not replace it: both exist, and the subclass one hides the parent's. Which one a read finds is decided by the declared type, at compile time, unlike an overridden method, which is chosen by the object.

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:

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.

a is declared Animal, so a.name is the parent's field. 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.