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

The 'Through Inheritance' Restriction

Understand why a subclass can't access protected members of sibling instances from other packages.

The 'Through Inheritance' Restriction

What you'll learn: You'll understand why a subclass can't access protected members of sibling instances from other packages, even though both share the same superclass.

The Surprising Limitation

You've learned that protected members are accessible to subclasses across packages. However, there's a critical restriction: a subclass can only access protected members through its own inherited instance, not through references to other instances of sibling classes.

Why This Matters

Imagine Parent class in package com.library has a protected field. Your ChildA class in com.myapp extends Parent. So far, so good—you can access that protected field in ChildA.

But what if you create a ChildB class (also extending Parent, also in com.myapp) and try to access the protected member of a ChildB instance from within ChildA? Java blocks this.

The Rule in Plain English

A subclass in a different package can access protected members only:

  • On this (the current instance)
  • On instances explicitly known to be of the subclass's own type
  • Through inherited members acting on the subclass itself

It cannot access protected members on:

  • Instances of sibling classes (other subclasses of the same parent)
  • Instances of the parent class itself from another package

Why Java Enforces This

This restriction prevents you from "breaking into" objects you shouldn't control. Just because two classes share a parent doesn't mean one sibling should freely manipulate another sibling's internal state across package boundaries. The "through inheritance" rule ensures protected truly means "for your own use as a subclass," not "for inspecting your cousins."

Key Takeaway: Protected access across packages is limited to the subclass's own inherited members—you cannot access protected fields or methods on sibling class instances or direct parent instances from another package, even within your subclass code.