10

我正在阅读:http:
//java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.20.2

他们说:

考虑示例程序:

class Point { int x, y; }
class Element { int atomicNumber; }
class Test {
        public static void main(String[] args) {
                Point p = new Point();
                Element e = new Element();
                if (e instanceof Point) {       // compile-time error
                        System.out.println("I get your point!");
                        p = (Point)e;           // compile-time error
                }
        }
}

instanceof表达式不正确,因为没有 的实例Element或其任何可能的子类(此处未显示)可能是 的任何子类的实例Point

为什么这会导致错误,而不是简单地instanceof返回 false?

谢谢,

杰拉格

4

4 回答 4

13

instanceofcheck 是运行时检查。编译器能够在编译时(更早)发现此条件不正确,因此它会告诉您它是错误的。永远记住,快速失败是一种很好的做法,它会为你节省很多时间和精力。

于 2010-12-16T11:42:33.010 回答
11

我会说,因为你在编译时就知道它永远不会是真的。因此,可以肯定地假设这不是程序员的意思:)

但是,可能有更多的 Java 技术解释。

于 2010-12-16T11:40:03.513 回答
4

因为编译器知道一个元素不可能是一个点,所以你得到一个编译错误。

于 2010-12-16T11:40:17.633 回答
1

因为继承树。如果 A 从 B 继承,那么您可以编写 B 的 A 实例

Integer i = 3;

System.out.println(i instanceof String); // compile time error

System.out.println(i instanceof Number); // true

System.out.println(i instanceof Object); // true
于 2010-12-16T11:41:05.490 回答