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:
- Package access: Any class in the same package can access
protectedmembers (just like package-private) - Inheritance access: Any subclass, even in a different package, can access
protectedmembers
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 subclassespublic→ 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.