instanceof是Java的一個二元運算子(運算子),也是Java的保留關鍵字。它的作用是判斷其左邊物件是否為其右邊類別的實例,而傳回的是boolean類型的資料。用它來判斷某個物件是否是某個Class類別的實例。
用法:
boolean result = object instanceof class
參數:
result :boolean類型。
object :必選項。任意物件表達式。
class:必選項。任意已定義的物件類別。
說明:
如果該object 是該class的一個實例,那麼傳回true。如果該object 不是該class的實例,或是object是null,則傳回false。
範例:
package com.instanceoftest; interface A { } class B implements A { } //B是A的实现 class C extends B { } //C继承B class D { } class instanceoftest { public static void main(String[] args) { A a = null; B b = null; boolean res; System.out.println("instanceoftest test case 1: ------------------"); res = a instanceof A; System.out.println("a instanceof A: " + res); // a instanceof A:false res = b instanceof B; System.out.println("b instanceof B: " + res); // b instanceof B: false System.out.println("\ninstanceoftest test case 2: ------------------"); a = new B(); b = new B(); res = a instanceof A; System.out.println("a instanceof A: " + res); // a instanceof A:true res = a instanceof B; System.out.println("a instanceof B: " + res); // a instanceof B:true res = b instanceof A; System.out.println("b instanceof A: " + res); // b instanceof A:true res = b instanceof B; System.out.println("b instanceof B: " + res); // b instanceof B:true System.out.println("\ninstanceoftest test case 3: ------------------"); B b2 = new C(); res = b2 instanceof A; System.out.println("b2 instanceof A: " + res); // b2 instanceof A:true res = b2 instanceof B; System.out.println("b2 instanceof B: " + res); // b2 instanceof A:true res = b2 instanceof C; System.out.println("b2 instanceof C: " + res); // b2 instanceof A:true System.out.println("\ninstanceoftest test case 4: ------------------"); D d = new D(); res = d instanceof A; System.out.println("d instanceof A: " + res); // d instanceof A:false res = d instanceof B; System.out.println("d instanceof B: " + res); // d instanceof B:false res = d instanceof C; System.out.println("d instanceof C: " + res); // d instanceof C:false res = d instanceof D; System.out.println("d instanceof D: " + res); // d instanceof D:true } }
#
以上是詳解java中的instanceof用法的詳細內容。更多資訊請關注PHP中文網其他相關文章!