Java之instanceof关键字

instanceof关键字用法

instanceof运算符的前一个操作符是一个引用变量,后一个操作数通常是一个类(或者接口) 用于判断前面的对象是否是后面的类、或者其子类、实现类的实例。 如果是返回true,否则返回false。

使用instanceof关键字做判断时, instanceof 操作符的左右操作数必须有继承或实现关系

定义接口IMammal,接口的实现类Whale
定义普通类Father,及其子类Son

interface IMammal{}
class Father{}
class Whale implements IMammal{}
class Son extends Father {}

public class Test {

	public static void main(String[] args) {
	//instanceof 用于判断一个对象是不是某个类或子类创建的;判断对象是不是一个接口的实现类创建的
		
		String str = "Jim";
		Son son = new Son();
		System.out.println(str instanceof String);
		System.out.println(str instanceof Object);
		System.out.println(son instanceof Son);
		System.out.println(son instanceof Object);
	}
}

结果:

true
true
true
true

但当比较的两个不存在继承或实现关系时:
一定要首先进行向上转型,然后才可用instanceof关键字进行判断,这是基本操作规范。

interface IMammal{}
class Father{}
class Whale implements IMammal{}
class Son extends Father {}

public class Test {

	public static void main(String[] args) {
		
		Object str = new String("Jim");//将String类型变量上转型为Object类型
		Object a = 1;
		Object son = new Son();//将Son类型变量上转型为Object类型
		System.out.println(str instanceof Son);
		System.out.println(son instanceof String);
		System.out.println(a instanceof Son);
		System.out.println(a instanceof Integer);
	}
}

结果:

false
false
false
true
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值