??下面是个例子:
public class InstanofTest {
public static void main(String[] args) {
//声明obj时使用Object类,则其编译类型是Object
//但obj运行时类型是String
Object obj = "hello";
//下面语句会返回true
System.out.println(obj instanceof Object);
//下面语句会返回true,String是Object类的子类,obj运行时类型是String,返回true
System.out.println(obj instanceof String);
//下面语句会返回false,Math是Object类的子类,但obj运行时类型是String
System.out.println(obj instanceof Math);
//下面语句在编译时不会报错,obj的编译类型是Object,是所有类包括Math类的父类
//但运行时会报ClassCastException异常,原因是obj运行时类型是String,无法转换成Math
Math m = (Math)obj;
String str = "hello";
//下面语句在编译时会报错,在Eclipse中编写该语句也会报错,str类型既不是Math类,也不是Math类的父类
System.out.println(str instanceof Math);
}
}
原文:https://www.cnblogs.com/xiejiafan/p/11289016.html