Course contentsShow
← Java
Lesson 720 of 2,87017. Access Control in DepthFree lesson

Shadowing Fields and Access Control

Subclass fields can shadow superclass fields; access control applies independently to each declared field.

Shadowing Fields and Access Control

What you'll learn: How subclass fields can hide superclass fields with the same name, and how access control applies independently to each shadowed field.


The Core Idea

When a subclass declares a field with the same name as a field in its superclass, the subclass field shadows (hides) the superclass field. Unlike method overriding, both fields actually exist — the subclass doesn't replace the superclass field, it just creates a new one with the same name. Critically, each field has its own access modifier, and access control is enforced separately for each.

Think of it like two people with the same name living in a house: the younger one doesn't erase the older one from existence; they're both there, but when someone calls that name, the nearest person responds first.


How Access Control Works with Shadowing

Each field in the shadowing relationship retains its own access level:

  • The superclass field keeps its original access modifier (private, package-private, protected, or public)
  • The subclass field has its own, potentially different access modifier
  • When you access the field through a subclass reference, you use the subclass field (subject to its access rules)
  • When you explicitly access through a superclass reference or use super.fieldName, you use the superclass field (subject to its access rules)

For example, a superclass might have a protected field named value, and the subclass might shadow it with a private field also named value. The protected field still exists and can be accessed using super.value (following protected rules), while the subclass value follows private rules.


Key Takeaway: Field shadowing creates two distinct fields with the same name; each field maintains its own independent access control, and which field you access depends on the reference type or whether you use the super keyword.