5
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
  • 1
    what do you mean, an error? it should just return false. Commented Mar 25, 2021 at 8:49

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Worth noting that if C was an interface, the compiler would let that instanceof through even if B didn't implement it.
@ernest_k that's true, since even if B doesn't implement C, a sub-class of B might implement it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.