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

前端 未结 4 1407
迷失自我
迷失自我 2020-12-11 17:58

I\'m reading this:
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.20.2

They say:

Consider the example program

相关标签:
4条回答
  • 2020-12-11 18:11

    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.

    0 讨论(0)
  • 2020-12-11 18:13

    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
    
    0 讨论(0)
  • 2020-12-11 18:30

    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.

    0 讨论(0)
  • 2020-12-11 18:38

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

    0 讨论(0)
提交回复
热议问题