Why does `instanceof` error rather than return `false` when used for 2 incompatible classes?

允我心安 提交于 2019-11-28 13:35:08
Vladimir Ivanov

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.

I'd say, because you know at compile-time that it will never be true. Therefore, it's safe to assume this is not what the programmer meant :)

However, there probably is a more java-technical explanation.

Because the compiler knows that is impossible to an Element be a Point, so you get an compilation error.

Because of the inheritance tree. if A inherited from B then you can write A instance of B

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!