Java access modifiers implicitly gives access priority to packages over subclasses since the default modifier gives access to packages but not to subclasses, protected permits access to both, but there is no modifiers which permits access to subclasses but not to packages. This has always felt weird to me, because I naturally tend to consider subclasses "closer" to the parent (even because they are their own variables after all) then the classes in the same package, and often I find myself in the situation where I would like to have the modifier for sub but not for the package. This probably means I use packages in a "wrong" way, but can someone explain me the logic behind this decision?
When you're using the protected
modifier, you're giving unlimited access to the class. It will be possible to extend it whenever you wish to even if the class would be inappropriate for subclassing. When you use the protected
modifier, you essentially say that the class will (for the forseeable future) always be appropriate for subclassing. This might not be something that you want; for example if you have a class that is supposed to get extended a few times for a project, and no more after that.
When you have no modifier (default-access/package-private), you are giving limited access to the class. Nobody, not even you, will have access to that class outside of the package, which is something you would want if you're doing something like the above case, where the class is specific to your project and extending it for any other arbitrary project would be inappropriate. Here is a list from highest access to lowest access:
public
: Unlimited access to everyone and everythingprotected
: Unlimited access but more restrictiveprivate
: Extremely limited access: not accessible by anything whatsoeverTo have a fifth access modifier between protected
and default-access so that every class anywhere that wishes to extend it should have access to it, but not have access if they don't want to extend it is redundant, because it already exists in the form of public abstract
.