Card 05/ 09
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:
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());animal dogThere 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.
← → move through sections and cards