'instanceof' 运算符对接口和类的行为不同 [英] The 'instanceof' operator behaves differently for interfaces and classes

查看:31
本文介绍了'instanceof' 运算符对接口和类的行为不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 Java 中 instanceof 运算符的以下行为.

I would like to know regarding following behavior of instanceof operator in Java.

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 Cclass B 之间没有关系,但是它给出false 而在obj instanceof A 的情况下它给出编译器错误?>

Why is it so? There is no relation between interface C and class B, but it gives false whereas in case of obj instanceof A it gives compiler error?

推荐答案

因为 Java 没有多类继承,所以在编译过程中绝对知道 obj 类型为 B 的对象不能是 A 的子类型.另一方面,它可能是接口 C 的子类型,例如在这种情况下:

Because Java has no multiple class inheritance it's absolutely known during the compilation that obj object of type B cannot be subtype of A. On the other hand it possibly can be subtype of interface C, for example in this case:

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 添加显式转换:

So looking only at obj instanceof C expression compiler cannot tell in advance whether it will be true or false, but looking at obj instanceof A it knows that this is always false, thus meaningless and helps you to prevent an error. If you still want to have this meaningless check in your program, you can add an explicit casting to the Object:

System.out.println(((Object)obj) instanceof A);      //compiles fine

这篇关于'instanceof' 运算符对接口和类的行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆