当用于2个不兼容的类时,为什么`instanceof`错误而不是返回`false`? [英] Why does `instanceof` error rather than return `false` when used for 2 incompatible classes?

查看:795
本文介绍了当用于2个不兼容的类时,为什么`instanceof`错误而不是返回`false`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读这个:

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




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

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.

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

Why does this result in an error, rather than simply in instanceof returning false?

谢谢,

JDelage

推荐答案

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

instanceof check is a runtime check. The compiler is able to discover that this condition is incorrect at compile time (much earlier), so it tells you that it is wrong. Always remember, that failing fast is a good practice, it will save you a lot of time and nerves.

这篇关于当用于2个不兼容的类时,为什么`instanceof`错误而不是返回`false`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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