instanceof运算符 - 为什么存在非法编译时错误 [英] instanceof operator - why there is Illegal compile time error

查看:184
本文介绍了instanceof运算符 - 为什么存在非法编译时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码,我不明白为什么System.out.println(c2 instanceof D);
将导致非法编译时间错误但不返回false?非常感谢您的帮助!

Considering the following code, I don't understand why "System.out.println( c2 instanceof D);" will result an "illegal compile time error" but not return "false"? Many thanks for your help!

interface I { }
class A { int x = 1;}
class B extends A implements I { int y = 2;}
class C extends B { }
class D extends B{ }
class E implements I { }
C c2 = new C();`


推荐答案

Java 8的错误是:

The error from Java 8 is:

error: incompatible types: C cannot be converted to D

实际上, C D 不在同一个血统中(除了对象)。由于编译器可以在编译时告诉你 instanceof 永远不会是真的,它确实如此。问题越早发现越好;编译器阻止您拥有不必要的代码或永远不会满足的条件。这就像你得到的代码永远无法达到的错误,因为逻辑是明确的,并且从不允许执行代码(错误:无法访问的语句)。

And indeed, C and D are not in the same lineage (other than both being Object). Since the compiler can tell you at compilation time that the instanceof will never be true, it does. The earlier a problem is caught, the better; the compiler is preventing your having code that is unnecessary or a condition that will never be satisfied. It's like the error you get when you have code that can never be reached because the logic is unambiguous and never allows execution of the code (error: unreachable statement).

这是一个完整的例子:

public class Example {

    interface I { }
    static class A { int x = 1;}
    static class B extends A implements I { int y = 2;}
    static class C extends B { }
    static class D extends B{ }
    static class E implements I { }

    public static final void main(String[] args) {
        C c2 = new C();
        System.out.println(c2 instanceof D);
    }
}

哪个失败了:

Example.java:12: error: incompatible types: C cannot be converted to D
        System.out.println(c2 instanceof D);

但是,如果您这样做,编译器无法确定 instanceof 将始终为false,那么它确实如此确实编译,你在运行时得到 false

But, if you make it so the compiler can't know for sure that the instanceof will always be false, then it does indeed compile and you get false at runtime:

public class Example {

    interface I { }
    static class A { int x = 1;}
    static class B extends A implements I { int y = 2;}
    static class C extends B { }
    static class D extends B{ }
    static class E implements I { }

    public static final void main(String[] args) {
        C c2 = new C();
        doTheCheck(c2);
    }

    static void doTheCheck(Object o) {
        System.out.println(o instanceof D);
    }
}

由于我们正在检查, o ,可能是任何东西,编译器不会提醒您进行不变检查,代码编译,并且您得到 false 作为输出。

Since what we're checking, o, could be anything, the compiler doesn't alert you to the invariant check, the code compiles, and you get false as output.

这篇关于instanceof运算符 - 为什么存在非法编译时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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