Core Java: Field hiding resolves by the reference's static type, unlike overridden methods

Accessing a field through a superclass-typed reference reads the superclass's field, because fields are hidden rather than overridden, while a method call still dispatches to the subclass's override.

Code
class Animal {
    String kind = "animal";
    String speak() { return "..."; }
}
class Dog extends Animal {
    String kind = "dog";
    String speak() { return "Woof"; }
}
Animal a = new Dog();
System.out.println("a.kind (field) = " + a.kind);
System.out.println("a.speak() (method) = " + a.speak());
Output
a.kind (field) = animal
a.speak() (method) = Woof
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms