Java instanceof 運算子的使用方法

來源:互聯網
上載者:User

用法:

  (類型變數 instanceof 類|介面)

作用:

  instanceof 操作符用於判斷前面的對象是否是後面的類,或者其子類、實作類別的執行個體。如果是則返回true 否則就返回false。

注意:

  · instanceof前面的運算元的編譯時間類型要麼與後面的類相同,要麼與後面的類具有父子繼承關係否則會引發編譯錯誤。

一個簡單的例子:

複製代碼 代碼如下:/**
* instanceof 運算子
* @author Administrator
*
*/

public class TestInstanceof {
public static void main(String[] args) {
//聲明hello 時使用Object類,則hello的編譯類型是Object
//Object類是所有類的父類,但hello的實際類型是String
Object hello = "Hello";

//String是Object的子類可以進行instanceof運算,返回true
System.out.println("字串是否為object類的執行個體:"
+ (hello instanceof Object));

//true
System.out.println("字串是否為String的執行個體:"
+ (hello instanceof String));

//false
System.out.println("字串是否為Math類的執行個體:"
+ (hello instanceof Math));

//String實現了Comparable介面,所以返回true
System.out.println("字串是否為Comparable類的執行個體:"
+(hello instanceof Comparable));

/**
* String 既不是Math類,也不是Math類的父類,故下面代碼編譯錯誤
*/
//String a = "hello";
//System.out.println("字串是否為Math類的執行個體:"
// + (a instanceof Math));

}
}

運行結果:

複製代碼 代碼如下:字串是否為object類的執行個體:true
字串是否為String的執行個體:true
字串是否為Math類的執行個體:false
字串是否為Comparable類的執行個體:true

通常在進行強制類型轉換之前,先判斷前一個對象是不是後一個對象的執行個體,是否可以成功轉換,從而保證代碼的健壯性。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.