When implementing something you will normally want to reduce the "attack surface" and not expose implementation details. This is why different access levels are needed. The reason for protected
is inheritance. We need something which is more strict than public
(to hide implementation details), but less strict than private
- so that subclasses would have access.
I think this logic is best explained by JLS §6.6.2. Details on protected Access:
A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
I think this should explain the logic of "class, package, subclass in same or different package":
- class should be clear, the class itself should of course have access to its members.
- subclass (same or different package) is also understandable.
- package is not so logical, to be honest. Possible explanation: it is likely that other classes in the same package will be used in the implementation of this object.
I agree that protected
is somewhat illogical. It combines restrictions on horizontal access (this package/other package) with restrictions on vertical access (subclass/not subclass).
And what if both parent and child classes are in the same package, does call by inheritance is only allowed option as well?
No. Other classes from the same package also have access to protected members of this class.
Also why it's not allowed to access A's protected methods for another class (B) from a different inheritance tree (C)?
This is specifically the intention of protected
. This is done to hide implementation details of A
from the "outside world".