通过instanceof运算符运算后得到的结果为布尔类型。instanceof前一个操作数A通常是一个引用类型的变量,后一个操作数B通常是一个类或者接口,用于判断对象A是否是B的类,或者其子类、实现类的实例。
' 在编译时,如果A的类型和B相同,或者是B的父类,编译才不会发生错误。例子程序如下:
public class Test{public static void main(String [] args){
//Object 类是所有类的父类
Object hello="Hello";
//hello变量的实际类型是String,String是Object的子类,可以进行instanceof运算,返回true
System.out.println("字符串是否是Object类的实例:"+(hello instanceof Object));
// hello变量的实际类型是String,返回true
System.out.println("字符串是否是String类的实例:"+(hello instanceof String));
//Math是Object的子类,可以进行instanceof运算。返回false
System.out.println("字符串是否是Math类的实例:"+(hello instanceof Math));
//String实现了Comparable接口,返回true
System.out.println("字符串是否是Comparable接口的实例:"+(hello instanceof Comparable));
//hello变量的编译类型是Object,是String类型的父类,可以强制类型转换
String x=(String) hello;
//String类既不是Math类,也不是Math父类,所以下面的代码编译会发生错误"Incompatible conditional operand types String and Math"
// System.out.println("字符串是否是Math类的实例:"+(x instanceof Math));
}
}
instanceof的作用:在执行强制类型交换之前,首先判断前一个对象是否是后一个类的实例,是否可以成功地转换,从而保证代码更加健壮。