Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

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

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:

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.

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

Thanks,

JDelage

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...