Java中instanceof关键字的理解

须知
  • instanceof 是一个双目运算符,使用格式:对象(引用变量) instanceof 类/接口
  • 是用来在运行时判断对象是否是特定类的一个实例,如果是返回true,否则返回false。
实例

有下面几个接口和类:

public interface AInterface {

}

public class FatherClass implements AInterface {
	
}

public class SonClass extends FatherClass {
	
}

public class OtherClass implements AInterface {

}

对应的关系图如下:
在这里插入图片描述
具体实例如下:

  1. 用接口做引用类型,用子类做实例对象

    		// 接口引用,子类实例
    		AInterface af = new SonClass();
    		System.out.println(af.getClass());// class com.hqq.instance_of.SonClass
    		System.out.println(af instanceof AInterface);// true
    		System.out.println(af instanceof FatherClass);// true
    		System.out.println(af instanceof SonClass);// true
    
    
  2. 用父类做引用类型,用子类做实例对象

    		// 父类引用,子类实例
    		FatherClass fc = new SonClass();
    		System.out.println(fc.getClass());// class com.hqq.instance_of.SonClass
    		System.out.println(fc instanceof AInterface);// true
    		System.out.println(fc instanceof FatherClass);// true
    		System.out.println(fc instanceof SonClass);// true
    
  3. 用子类做引用类型,子类做实例对象

    		// 子类引用,子类实例
    		SonClass sc = new SonClass();
    		System.out.println(fc.getClass());// class com.hqq.instance_of.SonClass
    		System.out.println(sc instanceof AInterface);// true
    		System.out.println(sc instanceof FatherClass);// true
    		System.out.println(sc instanceof SonClass);// true
    
  4. 接口做引用类型,父类做实例对象

    		// 接口引用,父类实例
    		AInterface a = new FatherClass();
    		System.out.println(a.getClass());// class com.hqq.instance_of.FatherClass
    		System.out.println(a instanceof AInterface);// true
    		System.out.println(a instanceof FatherClass);// true
    		System.out.println(a instanceof SonClass);// false
    
  5. 用接口做引用类型,other类做实例对象

    		AInterface ai = new OtherClass();
    		System.out.println(ai.getClass());// class com.hqq.instance_of.OtherClass
    		System.out.println(ai instanceof AInterface);// false
    		System.out.println(ai instanceof FatherClass);// false
    		System.out.println(ai instanceof SonClass);// false
    		System.out.println(ai instanceof OtherClass);// true
    
    
总结
  1. instanceof运算符的前一个操作符是一个引用变量(指向一个对象),后一个操作数通常是一个类(可以是接口)
  2. 用于判断前面的对象是否是后面的类,或者其子类、实现类的实例。也就是说:前面的对象,是后面:接口的实现类的对象、或者类本身的对象、或者类的子类的对象,就会返回true,否则返回false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yelvens

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值