In Java, we have four access specifiers: public
, protected
, package-private (default), and private
. This is well known and not an issue for me.
My question is with regard to the naming of protected
. As shown in the table here, giving a field the default access specifier of package-private prevents subclasses outside of the package from using it, but applying the keyword protected
doesn't actually protect it – on the contrary, it opens it up to subclasses of any package.
So, why doesn't protected
protect things; why is it less restrictive than no modifier at all?
If we accept that those are the four access levels that should exist (private, package-private, package-private-plus-subclasses, and public), and we accept that package-private should be the default access level when you don't specify something else, then this question becomes: "why is package-private-plus-subclasses called protected
?" And the answer to that is that it borrowed/inherited the term from C++ (which doesn't have a concept of "packages", but uses protected
to mean "private-plus-subclasses").
(I'm posting this answer as community wiki to encourage others to add to it, since I'm guessing that there's more to the story than just this. Also, because someone may want to add some justification of why these are the four access levels that should exist — e.g., why we have package-private-plus-subclasses but no private-plus-subclasses — and of why package-private should be the default.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With