In his book, Herbert Schildt says in page 172 (3rd paragraph) that "protected applies only when inheritance is involved.".
There's an argument that that statement is correct, although I'd say it's quite misleading. Let's look at the access chart from the access control tutorial:
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Note that no modifier grants both class and package access to the member, and does not grant access to subclasses or the world. protected
only changes one of those things: It makes the member available to subclasses. So in that sense, he's correct: It only applies when inheritance is involved; without inheritance, it's the same as having no modifier.
But I find it quite misleading, for the very reason that inspired your question: It seems to imply that there won't be package access. The only way the statement makes sense is if you already know that no modifier grants package access.
For clarity: protected
means a member is available to any class in the package and to code in subclasses. Doing this makes it possible for a library to have fields and methods you only access from code that's part of the library* (sort of, see below) or code that helps implement something in the library (for instance, if you're subclassing from one of the library classes). There's no particular "why" other than that's how the language was designed.
If it is so, then I find no difference between the public and protected specifiers in this situation.
In this situation, no. There's obviously quite a large difference, though, when you consider code that isn't in the same package and isn't in a derived class of a package member: That code has no access to protected
members.
This is covered in JLS§6.6.1:
...if the member or constructor is declared protected
, then access is permitted only when one of the following is true:
(note the first bullet) and JLS§6.6.2:
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.
("code that is responsible for the implementation of that object" — e.g., code in a subclass.)
* Re my "sort of, see below" on "Doing this makes it possible for a library to have fields and methods you only access from code that's part of the library..." That's not really true, because except for the restricted packages (java.lang
, for instance), you can happily write your own class saying it's in the library's package, and then use the package level fields and methods of the library's classes. Java's package concept is not a field/method security mechanism.