[Solved] Java – interface -instsnceof


JLS 15.20.2 states:

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error (§15.16), 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.

In this case (Intf) obj is not a compile time error because JLS 15.16 states:

If the compile-time type of the operand cannot be converted by casting conversion (§5.5) to the target type specified by the cast operator, then a compile-time error occurs.

So why is the cast not a compilation error?

Because while the static type of obj is A, the actual could be A or any subclass of A. And subclasses of A could implement Intf !!

Now we can see that is impossible in this context because obj has been initialized with a reference to an A instance …. but the type checker is not permitted to make that logical inference. (Or at least if it does, it can only treat it as a Warning not an Error.)

1

solved Java – interface -instsnceof