我想知道Java中 instanceof
运算符的以下行为。
interface C {}
class B {}
public class A {
public static void main(String args[]) {
B obj = new B();
System.out.println(obj instanceof A); //Gives compiler error
System.out.println(obj instanceof C); //Gives false as output
}
}
为什么会这样? interface C
和 class B
之间没有关系,但它给出 false 而在 obj instanceof A
的情况下它给出编译器错误?
最佳答案
因为Java没有多类继承,所以在编译过程中绝对知道B
类型的obj
对象不能是A
的子类型。另一方面,它可能是接口(interface) C
的子类型,例如在这种情况下:
interface C {}
class B {}
class D extends B implements C {}
public class A {
public static void main(String args[]) {
B obj = new D();
System.out.println(obj instanceof C); //compiles and gives true as output
}
}
所以只看obj instanceof C
表达式编译器无法提前判断它是真还是假,但是看obj instanceof A
就知道这总是false,因此毫无意义,并帮助您防止错误。如果您仍然希望在程序中进行这种无意义的检查,可以向 Object
添加显式转换:
System.out.println(((Object)obj) instanceof A); //compiles fine
关于java - 'instanceof' 运算符对接口(interface)和类的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31398444/