import static java.lang.System.*; public class InstanceofTest{ public static void main(String[] args){ //-引用變量hello的編譯類型為Object,實際類型為String,Object類為所有類的父類 Object hello="hello"; //-String 與Object存在繼承關系,可以進行 instanceof 計算,返回true out.println(hello instanceof Object); //-hello實際類型為String,可以進行 instanceof 計算,返回true out.println(hello instanceof String); //-Math與Object存在繼承關系,可以進行 instanceof 計算 //-但hello實際類型為String,與Math不存在繼承關系,不能轉換,所以返回false out.println(hello instanceof Math); //-String類型實現了Comparable接口,可以進行 instanceof 計算,返回true out.println(hello instanceof Comparable); //-a為徹頭徹尾的String 類型,與Math不存在繼承關系,不可以進行 instanceof 計算,編譯就不會通過,會報錯 String a="hello"; //out.println(a instanceof Math); } }
運行結果:
總結:
1、用於判斷前面的對象是否是后面的類,或者其子類、實現類的實例,是,返回true,不是,返回false
2、前面對象的編譯時類型,要么與后面 的類相同,要么與后面的類具有父子繼承關系,否則會引起編譯錯誤