baby-zhude

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、前面对象的编译时类型,要么与后面 的类相同,要么与后面的类具有父子继承关系,否则会引起编译错误

分类:

技术点:

相关文章:

  • 2021-07-04
  • 2022-12-23
  • 2021-12-09
  • 2021-12-22
  • 2021-11-14
  • 2022-02-07
猜你喜欢
  • 2022-02-18
  • 2021-11-29
  • 2021-12-12
  • 2021-11-26
  • 2022-02-13
  • 2021-05-04
  • 2022-12-23
相关资源
相似解决方案