Why does instanceof on Java give a compilation error?

Viewed 74
class A {}
class B extends A {}
class C extends A {}
A x = new B();
B y = new B();
x instanceof C
y instanceof C

Why does y instanceof C give a compilation error (incompatible types) when x instanceof C works fine?

1 Answers

When the compiler can tell that y instanceof C can never return true, it produces a compilation error. The compile time type of y is B, and class B has no relation to class C. Therefore, an instance of class B can never be an instance of class C.

On the other hand, x instanceof C may return true, since the compile time type of x is A, and C is a sub-clsss of A.

JLS refrence:

15.20.2. Type Comparison Operator instanceof

If a cast 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.

Related