In Java, there are four available access modifiers for methods:
public - any class can use this method.
protected - classes in the same package and subclasses in any package can use this method.
private - only this class can use this method.
no modifier ("package private") - only classes in the same package can use this method.
What happens often is that I want to have useful methods in a superclass, that all subclasses can use. But it wouldn't make sense for other classes to access this method, and in a sense it would break encapsulation.
So I have to declare these useful methods in the superclass
protected, which exposes them to all other classes at least in the package. Even though they're only meant to be used by the subclasses.
Is there a reason why there isn't a
subclasses-only access modifier in Java? It seems very odd to me. Am I missing something?
subclasses-only access modifier would also be useful for when you want to expose variables only to subclasses. Which to me happens a lot.