If you want to figure out protect member access, DO NOT skip the example here!
If a member of a class is declared protected, it is accessible to all classes within the package (the same as the default package accessibility) and also accessible within the body of any subclass of the class, regardless of the package in which that subclass is defined.
If a member of a class is not declared with any of these modifiers, it has default access (sometimes called package access) and it is accessible to code within all classes that are defined in the same package but inaccessible outside of the package.引自 Access to member
The statements seem clear at the first sight, but it is kind of confusing.
Be sure to read the example of B extends A.
In class B, the examine(A a), the a.name would caused a compile error, because instances of B do not have access to arbitary instances of A.
But change to
public String examine(B b) {
return "B sees another B:" + b.name;
}
will work, because instances of the same exact type can always see each other’s protected fields. Of course, if B was in the same package as A then any instance of B could read any protected field of any instance of A because protected fields are visible to every class in the same package. (Which mean change the package of class B to test1, the implementation of above picture a.name will work)