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?
The compiler knows at compile time that
childObj instanceof OtherClasswill never be true so the compiler fails fast and rejects the code.You could declare
childObjasObjectinstead and it should compile.For example: