Course contentsShow
← Java
Lesson 330 of 2,8708. Classes and EncapsulationFree lesson

protected: Inheritance and Package Access

Learn how protected grants access to subclasses and classes in the same package, bridging encapsulation and inheritance.

What You'll Learn

You'll learn how the protected access modifier grants access to subclasses and classes in the same package, creating a middle ground between encapsulation and inheritance.

The Bridge Between private and public

Think of protected as a family access pass. Where private locks the door to everyone and public leaves it wide open, protected says: "family members (subclasses) can enter, and so can neighbors in the same package."

The protected modifier serves two purposes:

  1. Package access: Any class in the same package can access protected members (just like package-private)
  2. Inheritance access: Any subclass, even in a different package, can access protected members

This makes protected particularly useful for methods and fields that subclasses need to override or use, but that you don't want to expose to the entire world.

When to Use protected

Use protected when:

  • You're designing a class meant to be extended
  • Subclasses need access to internal details to function properly
  • You want to hide implementation from unrelated classes

Example scenario: A Shape class might have a protected method calculateArea() that all shape subclasses need to implement or call, but external code shouldn't invoke directly.

Access Summary

  • private → only this class
  • package-private → this package only
  • protected → this package + all subclasses
  • public → everywhere

Key Takeaway: protected is the inheritance-friendly access level—it lets subclasses access members while maintaining encapsulation from unrelated classes, bridging controlled access with extensibility.