instanceof运算符

一 instanceof运算符两个注意点

  • 编译时,instanceof运算符前面操作数的编译时类型要么与后面类相同,要么与后面类具有父子继承关系。
  • instanceof前一个操作数通常是一个引用类型变量,后面一个操作数通常是一个类(接口),它用于判断前面对象是否是后面的类,或者其子类、实现类的实例。如果是,则返回true,否则返回false。

二instanceof应用

1 代码示例

public class InstanceofTest
{
	public static void main(String[] args)
	{
		// 声明hello时使用Object类,则hello的编译类型是Object,
		// Object是所有类的父类, 但hello变量的实际类型是String
		Object hello = "Hello";
		// String与Object类存在继承关系,可以进行instanceof运算。返回true。
		System.out.println("字符串是否是Object类的实例:"
			+ (hello instanceof Object));
		System.out.println("字符串是否是String类的实例:"
			+ (hello instanceof String)); // 返回true。
		// Math与Object类存在继承关系,可以进行instanceof运算。返回false。
		System.out.println("字符串是否是Math类的实例:"
			+ (hello instanceof Math));
		// String实现了Comparable接口,所以返回true。
		System.out.println("字符串是否是Comparable接口的实例:"
			+ (hello instanceof Comparable));
		String a = "Hello";
//		// String类与Math类没有继承关系,所以下面代码编译无法通过
//		System.out.println("字符串是否是Math类的实例:"
//			+ (a instanceof Math));
	}
}

 2 运行结果

字符串是否是Object类的实例:true

字符串是否是String类的实例:true

字符串是否是Math类的实例:false

字符串是否是Comparable接口的实例:true

原文地址:https://www.cnblogs.com/ainima/p/6331655.html