我讀這樣的:
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.20.2爲2個不兼容的類使用時,爲什麼`instanceof`錯誤而不是返回`false`?
他們說:
考慮的示例程序:
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
的任何子類的實例。
爲什麼這會導致錯誤,而不是簡單地在instanceof
返回false?
感謝,
JDelage
這聽起來像你以前的經驗可能與大多數鬆散類型和主要解釋的語言(例如:大多數BASIC),而不是強類型和編譯。使用大多數解釋的語言,幾乎所有的類型驗證都在運行時發生。但是,對於編譯語言,編譯器能夠完成相當多的「類型和執行流分析」。因此,如果發現永遠不能執行的路徑,它可以刪除該路徑中的代碼(即去除死代碼)。如果它發現一個不可能成功的操作,就會產生一個錯誤。 – chaotic3quilibrium 2010-12-16 16:36:59