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

Accessing Protected Members in Subclasses Across Packages

Learn that subclasses in other packages can only access protected members through their own instances.

Accessing Protected Members in Subclasses Across Packages

What you'll learn: How subclasses in different packages can access protected members, but only through their own inheritance chain—not through arbitrary instances of the parent class.

The Core Restriction

When a subclass exists in a different package than its parent, it gains a special but limited ability to access protected members. The key rule: a subclass can only access protected members through references of its own type (or its subtypes), not through references of the parent class type.

Think of it like a family heirloom: you inherit the right to use your family's protected treasures, but only your inherited copies—not your cousin's version from a different household.

Why This Matters

This restriction prevents one subclass from reaching into another unrelated subclass's inherited data. Without it, any subclass could manipulate protected members of any instance of the parent class, breaking encapsulation.

The Rule in Plain English

  • ✅ Allowed: this.protectedField or calling this.protectedMethod() in the subclass
  • ✅ Allowed: Accessing protected members through an object of the subclass type
  • ❌ Not allowed: Accessing protected members through a reference of the parent class type (even if it points to a subclass instance)

Example Scenario

If Parent (in package a) has a protected field, and Child (in package b) extends Parent, then inside Child:

  • You can access the protected field on this
  • You can access it on another Child instance
  • You cannot access it through a Parent reference variable (even if it actually holds a Child object)

Key Takeaway: Subclasses in different packages can only access protected members through their own type hierarchy, ensuring that inheritance doesn't become a backdoor to bypass encapsulation across package boundaries.