运算符的实例

此运算符检查对象是否属于特定的类/接口类型。 instanceof 运算符写成:

( Object reference variable ) instanceof  (class/interface type)

例:

public class Test {

   public static void main(String args[]){
      String name = "Buyya";
      // following will return true since name is type of String
      boolean result = name instanceof String;  
      System.out.println( result );
   }
}

这将产生以下结果:

true

如果要比较的对象是与右侧类型兼容的赋值,则此运算符仍将返回 true。

例:

class Vehicle {}

public class Car extends Vehicle {
   public static void main(String args[]){
      Vehicle a = new Car();
      boolean result =  a instanceof Car;
      System.out.println( result );
   }
}

这将产生以下结果:

true