Java – Why Is There No ‘Subclasses-Only’ Access Modifier in Java?

inheritancejavalanguage-featuresobject-oriented

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 public or 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?

Also, a subclasses-only access modifier would also be useful for when you want to expose variables only to subclasses. Which to me happens a lot.

Best Answer

Java originally had such a modifier. It was written private protected but removed in Java 1.0.

I assume that was a judgment call that the extra complexity wasn't worth the cost.

Every language feature has a cost: in teaching it to new programmers; in documentation; in implementing it in the compiler, JVM, and dev tools; in reasoning about program correctness; in constraining future language evolution; and more. Language features interact with each other, potentially with N2 interactions.

What percent of Java programmers have read through the Java language spec and VM spec? I bet it's a small percentage, which argues for an even simpler language for the sake of understandability and engineering products that we can depend on

The benefit of the private protected feature was small since the package is the main unit of modularity.