Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does instanceof on Java give a compilation error?

Tags:

java

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?

like image 619
NewbieToCoding Avatar asked Mar 25 '21 08:03

NewbieToCoding


People also ask

Is it good to use Instanceof in java?

Probably most of you have already heard that using “instanceof” is a code smell and it is considered as a bad practice. While there is nothing wrong in it and may be required at certain times, but the good design would avoid having to use this keyword.

How does Instanceof work in java?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

What does Instanceof return in java?

The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false.

Does Instanceof work for interfaces java?

instanceof can be used to test if an object is a direct or descended instance of a given class. instanceof can also be used with interfaces even though interfaces can't be instantiated like classes.


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.

like image 82
Eran Avatar answered Oct 16 '22 10:10

Eran