Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Java's "protected" less protected than default? [closed]

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?

like image 421
wchargin Avatar asked Dec 27 '22 06:12

wchargin


1 Answers

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.)

like image 176
ruakh Avatar answered Jan 10 '23 20:01

ruakh