Considering the following code, I don\'t understand why \"System.out.println( c2 instanceof D);\"
will result an \"illegal compile time error\" but not return \
Because compiler knows that casting c2
to type D
will always doing to fail at runtime, and hence is marked as compile time error. So it doesn't allow such instanceof
to pass through.
Quoting JLS §15.20.2:
If a cast (§15.16) of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.