Java OOP Design: How to Restrict Method Access to Specific Interfaces or Classes
Understanding the Encapsulation Challenge
Designing robust object-oriented systems often requires strict rules on which objects can mutate state. A common scenario in game development or domain modeling is wanting a specific action—such as healing a character—to be restricted exclusively to entities that possess a specific capability (e.g., implementing a Healable interface or extending a Healer class).
Standard Java access modifiers (public, protected, package-private, and private) don't natively offer a direct modifier like restricted to InterfaceX. If you make heal(int amount) public on GameCharacter, any character (like a Warrior or Dragon) can invoke it on themselves or others. Making it protected allows subclasses to call it on themselves, but fails when a Healer needs to heal a different subclass across packages.
Here are the most idiomatic Java design patterns and strategies to solve this problem while preserving encapsulation and type safety without resorting to instanceof checks.
Approach 1: The Capability / Token Pattern (Recommended)
The Capability Pattern restricts method execution by requiring a restricted token that only authorized classes can supply or instantiate. In Java, this can be achieved by requiring a reference to the Healable interface inside the health modification method.
Implementation Example