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?
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With