我正在测试JAVA“运算符实例”,以便刷新我的想法。我看到该关键字用于检查引用是否是类的实例。
但我们使用引用来比较与类没有任何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”关系一起使用那么...... if条件的变化在哪里是假的?
答案 0 :(得分:3)
这是一个功能,而不是一个bug。编译器会阻止您在基本上无法满足它的情况下使用instanceof
运算符,例如:
String s = "abc";
if(s instanceof Integer) {
}
s instanceof Integer
永远不会成真。但是,检查是在编译时执行的,因此编译:
Object s = "abc";
if(s instanceof Integer) {
}