天天看點

Java 中 instanceof 運算符的使用場景Instanceof 運算符的含義     

Instanceof 運算符的含義     

       Java 中的 instanceof 運算符可以指出對象是否是特定類的一個執行個體。在具體的語句中,instanceof 左邊是對象,右邊是類。若該對象是右邊類或子類所建立的,則傳回 true ,否則傳回 false。需要注意的是,instanceof 運算符左邊的對象執行個體不可以是基礎資料類型;null 與任何值進行運算均傳回 false。

       例如下列代碼段中,a 是接口 Test1 的執行個體對象引用指向子類 Test2,類 Test2 實作了接口Test1。是以兩次輸出的結果均為 true。

public interface Test1{
}

public class Test2 implements Test1{
}

public class Example{
    public static void main(String[] args){
        a = new Test2();
        b = new Test2();
        result = a instanceof Test1;
        System.out.println(result); 
        result = a instanceof Test2;
        System.out.println(result); 
    }
}