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

Protected Members and Package Boundaries

Explore how protected members are accessible within the package and to subclasses outside it.

Protected Members and Package Boundaries

What you'll learn: How protected members behave differently inside versus outside their package, giving access to both package-mates and distant subclasses.

The Dual Nature of protected

You've learned that protected members are visible to subclasses and package-mates. Now let's explore the boundary: what happens when a subclass lives in a different package?

The protected modifier actually grants two distinct access rights:

  1. Within the same package: Any class in the package can access the protected member (just like package-private)
  2. Outside the package: Only subclasses can access the protected member, and only through inheritance

The Package Boundary Effect

Think of protected as a "family pass" that works two ways:

  • Same neighborhood (package): Everyone can visit your house
  • Different neighborhood: Only blood relatives (subclasses) can visit

When a subclass is in a different package, it can access protected members of its parent class, but only on instances of itself or its own subclasses—not on arbitrary instances of the parent class.

Why This Matters

Inside the package, protected behaves generously—any class is a neighbor. Cross the package boundary, and protected becomes restrictive—inheritance is required. This allows you to:

  • Share implementation details freely within your package
  • Carefully expose extension points to external subclasses
  • Maintain encapsulation while enabling controlled inheritance

Key Takeaway:
protected members are accessible to all classes within the same package AND to subclasses in other packages (through inheritance), making the package boundary a critical dividing line in access control.