instanceof用法及本质:

import static java.lang.System.*;
public class InstanceofTest{
	public static void main(String[] args){
		//-引用变量hello的编译类型为Object,实际类型为String,Object类为所有类的父类
		Object hello="hello";
		//-String 与Object存在继承关系,可以进行 instanceof 计算,返回true
		out.println(hello instanceof Object);
		//-hello实际类型为String,可以进行 instanceof 计算,返回true
		out.println(hello instanceof String);
		//-Math与Object存在继承关系,可以进行 instanceof 计算
		//-但hello实际类型为String,与Math不存在继承关系,不能转换,所以返回false
		out.println(hello instanceof Math);
		//-String类型实现了Comparable接口,可以进行 instanceof 计算,返回true
		out.println(hello instanceof Comparable);

		//-a为彻头彻尾的String 类型,与Math不存在继承关系,不可以进行 instanceof 计算,编译就不会通过,会报错
		String a="hello";
		//out.println(a instanceof Math);
	}
}

运行结果:

总结:

1、用于判断前面的对象是否是后面的类,或者其子类、实现类的实例,是,返回true,不是,返回false

2、前面对象的编译时类型,要么与后面 的类相同,要么与后面的类具有父子继承关系,否则会引起编译错误

原文地址:https://www.cnblogs.com/baby-zhude/p/8040362.html