相关疑难解决方法(0)

当用于2个不兼容的类时,为什么`instanceof`错误而不是返回`false`?

我正在读这个: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
                }
        }
}
Run Code Online (Sandbox Code Playgroud)

instanceof表达不正确,因为没有的实例Element或它的任何可能的亚类(没有在这里示出)的可能可能是任子类的实例Point.

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

谢谢,

JDelage

java inheritance instanceof

7
推荐指数
2
解决办法
2175
查看次数

标签 统计

inheritance ×1

instanceof ×1

java ×1