Video in progress
Do fields behave polymorphically like methods? What happens if a parent and a child class have a field with the same name?
No, fields are not polymorphic. A field with the same name hides the parent's (field hiding), and which one is read is chosen at compile time by the declared type of the variable. Methods, on the other hand, are chosen by the actual type of the object.
📖 Answer
class Parent {
String name = "parent";
String getName() { return name; }
}
class Child extends Parent {
String name = "child"; // hiding
@Override String getName() { return name; }
}
Parent p = new Child();
System.out.println(p.name); // parent
System.out.println(p.getName()); // child
System.out.println(((Child) p).name); // child
Inside the object there are actually two name fields: one from Parent and one from Child. That is wasted memory and a source of confusion.
How this shows up in a real project: the parent class has protected Long id;, and someone adds a private Long id; to the child class too. The parent's methods read one id, the child's methods read the other, and the ID seems to "vanish". It hurts especially in JPA entities.
How to avoid it:
- make fields
privateand access them only through methods, so polymorphism works correctly through the methods; - turn on IntelliJ's "Field hides field in superclass" inspection.
Sign up to mark studied questions and save your progress.