Why the error is `instanceof`, and does not return` false` if used for 2 incompatible classes?

I read this:
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.20.2

They say:

Consider an 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 the Element or any of its possible subclasses (none of which are shown) can be an instance of any subclass of Point .

Why does this lead to an error, and not just an instanceof returning false?

Thanks,

Jdelage

+6
java inheritance instanceof
source share
4 answers

instanceof check is a runtime check. The compiler may find that this condition is incorrect at compile time (much earlier), so it tells you that it is wrong. Always remember that failure quickly is a good practice, it will save you a lot of time and nerves.

+10
source share

I would say because at compile time you know that this will never be true. Therefore, we can safely assume that this is not what the programmer meant :)

However, there may be a more detailed description of Java technologies.

+10
source share

Since the compiler knows that the element cannot be a point, so you get a compilation error.

+3
source share

Because of the inheritance tree. if A is inherited from B, you can write an 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
source share

All Articles