可能重复:
instanceof - 不兼容的条件操作数类型
我正在测试 JAVA “instance of”运算符,以刷新我的想法。我看到该关键字用于检查引用是否是类的实例。
但是我们使用引用来与与该类没有任何 IS-A 关系的类进行比较,然后它会给出编译时错误。
请参阅以下代码:
package instanceofdemo;
public class Sample_1 {
    public static void main(String a[]){
        A iface = new Subclass();
        ///HERE INTERFACE OBJECT IS DOWNCASTED TO SUBCLASS
        if(iface instanceof  SuperClass){
            System.out.println("iface instanceof  SuperClass");
        }
        ///HERE INTERFACE OBJECT IS DOWNCASTED TO SUBCLASS
        if(iface instanceof  Subclass){
            System.out.println("iface instanceof  Subclass");
        }
        if(iface instanceof  A){
            System.out.println("iface instanceof  A");
        }
        Subclass sub = new Subclass();
        //SO INSTANCE OF ONLY WORKS WITH IS-A RELATION SHIP IN BI-DIRECTIONAL WAY
        //IT WILL GIVE COMPILE TIME ERROR, IF YOU TRY TO USE INSTANCE-OF WITH NON-RELATED CLASS
        if(sub instanceof  Independent){
        }
    }
}
interface  A{
}
class SuperClass implements A {
}
class Subclass extends  SuperClass{
}
class Independent{
}
在上面的代码中:当它在if(iface instance of Independent)bcoz 行给出编译错误时,iface 与 Independent 没有“IS-A”关系。
那么关键字实例的确切用途是什么?如果它仅与“IS-A”关系一起使用,那么......如果条件为假的变化在哪里?