gpt4 book ai didi

java - instanceof 运算符 - 为什么会出现非法编译时错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:46:54 28 4
gpt4 key购买 nike

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

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 的错误是:

error: incompatible types: C cannot be converted to D

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).

Here's a complete example:

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);

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作为输出。

关于java - instanceof 运算符 - 为什么会出现非法编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25785873/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com