问题
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?
回答1:
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.)
回答2:
Since this is a rather open-ended question I'll offer some semi-relevant historical context. In Java 1.0 there was an additional access modifier, private protected. This was protected minus package access. This modifier was confusing, poorly implemented and removed by 1.1. This helps paint the picture that the package is the logical modular unit which is therefore the default level of access.
At the end of the day it comes down to a personal choice of what made sense to the developers. Everyone thinks differently so a naming convention that makes perfect sense to me may be deeply confusing for you (and vice versa).
回答3:
Protected is more restrictive than public. That is why it is called what it is.
I wish the language designers would have named the default access specifier as "package-protected', because the default is very confusing to a lot of programmers. I would more be in favor for protected being the default, or there being no default at all.
来源:https://stackoverflow.com/questions/15626321/why-is-javas-protected-less-protected-than-default