Java中的instanceof关键字
该运算符仅用于对象引用变量。运算符检查对象是否具有特定类型(类类型或接口类型)。instanceof运算符写为-
( Object reference variable ) instanceof (class/interface type)
如果运算符左侧变量所引用的对象通过了IS-A检查右侧类/接口类型的检查,则结果为true。以下是一个示例-
示例
public class Test {
public static void main(String args[]) {
String name = "James"; // 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
热门推荐
10 感动妈妈的祝福语简短
11 升学祝福语简短的个性
12 60岁长辈祝福语简短
13 甄嬛传祝福语简短
14 分手快乐祝福语简短
15 迎新祝福语简短20字
16 贺卡祝福语情侣搞笑简短
17 祝贺新店开业祝福语简短
18 离别祝福语简短送同事