This is the correct behavior. In fact, the Java Language Specification , section 6.6.2-1, has an example very similar to yours, with a comment that it should not compile.
Access to protected members is described in detail in Section 6.6.2.1:
6.6.2.1. Protected Member Access
Let C
be the class in which the protected member is declared. Access is permitted only inside the body of subclass S
C
In addition, if Id
denotes an instance field or instance method, then:
If access is by the qualified name Q.Id
, where Q
is an expression, then access is allowed if and only if the type of the expression Q
is S
or a subclass of S
If access is through an access expression to the field E.Id
, where E
is the primary expression or the call expression of the method E.Id(. . .)
, Where E
is the primary expression, then access is allowed if and only if type E
is equal to S
or subclass S
This is the last paragraph that describes why access is denied. In your example, C
has Base
, S
is BaseChild
and E
, the type of the Base
variable is also Base
. Since Base
is neither BaseChild
nor a subclass of BaseChild
, access is denied.
source share