Protected Reference Type Restrictions
What you'll learn: You'll understand why you can't just use any reference to access a protected member, even from a valid subclass.
The Core Idea
Even though you've inherited a protected member from a superclass and you're in a subclass across packages, Java restricts which references you can use to access it. You can access the protected member through this or through references of your own subclass type, but not through references typed as the unrelated superclass or sibling subclass.
Why This Restriction Exists
Protected access is granted to you because you're a subclass—it's about your inheritance relationship, not about giving you universal access to all instances of the superclass family tree. Java enforces that you can only access protected members on objects that are known to be part of your subclass hierarchy.
Plain English Example
Imagine you're a trusted employee (SubclassA) who gets special access to company resources because of your role. That doesn't mean you can access another department's resources (SubclassB instance) just because they're also employees under the same parent company.
What's Allowed and What's Not
- ✅ Allowed: Accessing through
this(implicitly or explicitly) - ✅ Allowed: Accessing through a reference of your own subclass type
- ❌ Blocked: Accessing through a superclass-typed reference pointing to a different subclass instance
- ❌ Blocked: Accessing through a sibling subclass reference
This prevents you from bypassing encapsulation by manipulating instances of other subclasses through their inherited protected members.
Key Takeaway:
Protected members are accessible in subclasses only through this or references of your own subclass type—not through arbitrary superclass or sibling references, maintaining proper encapsulation boundaries.