1. 程式人生 > >java中instanceof的用法

java中instanceof的用法

轉自https://www.cnblogs.com/bkyshichao/p/7090401.html 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
    }
  }