Why is there no sub-class visibility modifier in Java?
You should put your class in a package of it's own and mark the member(instance variable or method) as protected. This way no other classes, except the subclasses can access that member which you market as protected. You will end up with one class in one package, if you desperately want only subclasses to access that protected member.
I suppose they want to avoid the added complexity by having a non-linear access hierarchy.
You should have control over your package, so simply don't call these protected methods there.
(By the way, protected
is not quite the same as sub-class and package
, as non-static protected methods (if not in the same package) can't be called on arbitrary objects of the declaring class, but only on objects of the subclass the code is in. (You can see this on Object.clone()
, which can only be called by the class whose object is being cloned.))
Being-in-the-same-package is simply considered a closer relationship than being-a-subtype-of.
Why?
You typically control all source code of the package you're developing(*), so you at least have the possibility to avoid making erroneous calls.
You do not control all code that extends your classes. (Anyone can extend your class.) This means that package private access plays a more important role.
*) But hey, I an start any source file with package com.yourpackage;
so you don't control all code in your package! Well, yes, but a) you're not really supposed to do that, and b) it can be prevented by sealing the packages.