用法:
(類型變量 instanceof 類|接口)
作用:
instanceof 操作符用于判斷前面的對象是否是后面的類,或者其子類、實(shí)現(xiàn)類的實(shí)例。如果是則返回true 否則就返回false。
注意:
? instanceof前面的操作數(shù)的編譯時(shí)類型要么與后面的類相同,要么與后面的類具有父子繼承關(guān)系否則會(huì)引發(fā)編譯錯(cuò)誤。
一個(gè)簡單的例子:
public class TestInstanceof {
public static void main(String[] args) {
//聲明hello 時(shí)使用Object類,則hello的編譯類型是Object
//Object類是所有類的父類,但hello的實(shí)際類型是String
Object hello = "Hello";
//String是Object的子類可以進(jìn)行instanceof運(yùn)算,返回true
System.out.println("字符串是否為object類的實(shí)例:"
+ (hello instanceof Object));
//true
System.out.println("字符串是否為String的實(shí)例:"
+ (hello instanceof String));
//false
System.out.println("字符串是否為Math類的實(shí)例:"
+ (hello instanceof Math));
//String實(shí)現(xiàn)了Comparable接口,所以返回true
System.out.println("字符串是否為Comparable類的實(shí)例:"
+(hello instanceof Comparable));
/**
* String 既不是Math類,也不是Math類的父類,故下面代碼編譯錯(cuò)誤
*/
//String a = "hello";
//System.out.println("字符串是否為Math類的實(shí)例:"
// + (a instanceof Math));
}
}
新聞熱點(diǎn)
疑難解答
圖片精選