運算子的例項
此運算子檢查物件是否屬於特定的類/介面型別。 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