Avoiding protected: When Inheritance Leaks Implementation
What you'll learn: You'll discover why protected can unexpectedly expose implementation details and when composition is safer than inheritance.
The Hidden Cost of Protected
The protected modifier seems like a reasonable middle ground—more open than private, more controlled than public. But it creates a subtle problem: protected members become part of your class's contract with all future subclasses, anywhere in the codebase.
When you mark a field or method protected, you're essentially promising that:
- Subclasses can depend on it
- You can't easily change or remove it later
- Implementation details leak into your inheritance hierarchy
Analogy: Imagine lending your car to family members (protected). Once they know where you hide the spare key and how to disable the alarm, they'll rely on those details. If you change your security system, you break their expectations.
When Protected Breaks Encapsulation
Protected fields are especially problematic. A subclass in another package can directly access and modify them, bypassing any validation logic. Your carefully designed class can be undermined by inheritance.
Protected methods fare slightly better but still expose "how" your class works internally, not just "what" it does publicly.
The Alternative: Composition Over Inheritance
Instead of extending a class to reuse behavior, consider containing an instance of it as a private field. You control exactly which methods to expose, preserving encapsulation. This approach is more flexible—you can swap implementations without affecting the public interface.
When protected is acceptable: Template Method pattern scenarios where you explicitly design base classes for extension with well-documented extension points.
Key Takeaway: Use protected sparingly and only when designing explicit inheritance hierarchies; prefer private fields with public methods, or use composition instead of inheritance to avoid leaking implementation details across package boundaries.