加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么`instanceof`错误而不是在用于2个不兼容的类时返

发布时间:2020-12-15 02:48:36 所属栏目:Java 来源:网络整理
导读:我正在读这个: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.20.2 他们说: Consider the example program: class Point { int x,y; }class Element { int atomicNumber; }class Test { public static void main(String[] a
我正在读这个:
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.20.2

他们说:

Consider the example program:

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
                }
        }
}

The instanceof expression is incorrect because no instance of Element or any of its possible subclasses (none are shown here) could possibly be an instance of any subclass of Point.

为什么这会导致错误,而不是简单地在返回false的情况下?

谢谢,

JDelage

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读