instanceof cannot be used with any class?

80 views Asked by At

I am trying instanceof in Java. I declared three classes where one extends another as follows:

class ParentClass {
    // Class members
}
class ChildClass extends ParentClass{
    // Class members
}
class OtherClass {
    // Class members
}

instanceof works fine if it will give true as in the first three usages below. However, it gives "Incompatible conditional operand types error" when used with a class that will give false in the last statement:

public class JavaTest{
    public static void main(String[] args) {
        ChildClass childObj = new ChildClass();
        System.out.println(childObj instanceof ChildClass);
        System.out.println(childObj instanceof ParentClass);
        System.out.println(childObj instanceof Object);
        System.out.println(childObj instanceof OtherClass);
    }
}

What is the reason for that?

1

There are 1 answers

0
lance-java On

The compiler knows at compile time that childObj instanceof OtherClass will never be true so the compiler fails fast and rejects the code.

You could declare childObj as Object instead and it should compile.

For example:

Object childObj = new ChildClass();
System.out.println(childObj instanceof OtherClass);