java中instanceof關鍵字的用法

來源:互聯網
上載者:User

instanceof運算子的前一個運算元通常是一個參考型別變數,後一個運算元通常是一個類(也可以是介面,可以把介面理解成一種特殊的類),它用於判斷前面的對象是否是後面的類,或者其子類、實作類別的執行個體。如果是,則返回true,否則返回false。

在使用instanceof運算子時需要注意:instanceof運算子前面運算元的編譯時間類型要麼與後面的類相同,要麼與後面的類具有父子繼承關係,否則會引起編譯錯誤。

class BaseClass{}class SubClass extends BaseClass{}public class InstanceofTest{public static void main(String[] args){//聲明hello時使用Object類,則hello的編譯類型是Object//Object是所有類的父類,但hello變數的實際類型是StringObject hello = "Hello";System.out.println("字串是否是Object類的執行個體:"+(hello instanceof Object));System.out.println("字串是否是String類的執行個體:"+(hello instanceof String));System.out.println("字串是否是Math類的執行個體:"+(hello instanceof Math));System.out.println("字串是否是Comparable介面的執行個體:"+(hello instanceof Comparable));String a = "hello";//System.out.println("字串是否是Object類的執行個體:"+(a instanceof Math));BaseClass b = new BaseClass();SubClass aa = new SubClass();System.out.println(aa instanceof BaseClass);}}

結果:

字串是否是Object類的執行個體:true
字串是否是String類的執行個體:true
字串是否是Math類的執行個體:false
字串是否是Comparable介面的執行個體:true
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.