跳轉到內容

Java 程式設計/關鍵字/instanceof

來自華夏公益教科書,開放的書籍,開放的世界

instanceof 是一個關鍵字。

它檢查一個物件引用是否是一個型別的例項,並返回一個布林值;

<object-reference> instanceof Object 對於所有非空物件引用將返回 true,因為所有 Java 物件都繼承自 Objectinstanceof 如果 <object-reference> 是 null,則始終返回 false

語法

<object-reference> instanceof TypeName

例如

Computer code
class Fruit
 {
  //...	
 } 
 class Apple extends Fruit
 {
  //...
 }
 class Orange extends Fruit
 {
  //...
 }
 public class Test 
 {
    public static void main(String[] args) 
    {
       Collection<Object> coll = new ArrayList<Object>();
 
       Apple app1 = new Apple();
       Apple app2 = new Apple();
       coll.add(app1);
       coll.add(app2);
 
       Orange or1 = new Orange();
       Orange or2 = new Orange();
       coll.add(or1);
       coll.add(or2);
 
       printColl(coll);
    }
 
    private static String printColl( Collection<?> coll )
    {
       for (Object obj : coll)
       {
          if ( obj instanceof Object )
          {
             System.out.print("It is a Java Object and");
          }
          if ( obj instanceof Fruit )
          {
             System.out.print("It is a Fruit and");
          }
          if ( obj instanceof Apple )
          {
             System.out.println("it is an Apple");
          } 
          if ( obj instanceof Orange )
          {
             System.out.println("it is an Orange");
          }
       }
    }
 }

執行程式

java Test

輸出

"It is a Java Object and It is a Fruit and it is an Apple"
"It is a Java Object and It is a Fruit and it is an Apple"
"It is a Java Object and It is a Fruit and it is an Orange"
"It is a Java Object and It is a Fruit and it is an Orange"

請注意,instanceof 運算子也可以應用於介面。例如,如果上面的示例用介面增強了


Computer code
interface Edible 
{
 //...
}


以及修改後的類以實現此介面


Computer code
class Orange extends Fruit implements Edible
 {
  ...
 }


我們可以詢問我們的物件是否可食用。


Computer code
if ( obj instanceof Edible )
 {
   System.out.println("it is edible");
 }
華夏公益教科書