I am reading the book The Java Programming Language, 3rd edition.
In chapter 3.5 , it illustrates the protected
modifier with the following words:
More precisely, beyond being accessible within the class itself and to code within the
same package, a protected member can also be accessed from a class through object references
that are of at least the same type as the class that is, references of the class's type or
one its subtypes.
The words makes me confused, in two aspects:
1. protected member can be accessed by code within the same package ? What I knew before is protected member can only be accessed by the subclass...
2. I don't understand what does a protected member can also be accessed from ...
mean, anyone can explain to me please?
In Java, protected
means that the member can be accessed by any class in the same package and by subclasses even if they are in another packages.
Note
A protected variable is not visible outside the package
for example B extends A and A has a protected int x; it can be use within the class B. But cannot be access using its instance variable
1) Yes, protected members can be accessed by classes from the same package. That's the way Java works.
2) That means subclasses can access them.
I don't understand what does a protected member can also be accessed from ... mean, anyone can explain to me please?
For example, you have an object A and an object B, both of the same class. Object A will be able to query the protected properties and methods of object B if it has a reference to it. The protected modifier is enforced at class level, not at object level. This can come in handy in some situations.
Just think of it as between public and private. You can access everything from public classes, and less from private classes.