Java关键字--instanceof

本文详细解析了Java中instanceof操作符的使用规则,包括其在对象实例判断、null值处理、子类与父类及接口间比较的应用。通过具体示例,展示了不同类型转换与比较时的运行结果与编译行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

instanceof释义

instanceof用于判断一个对象是否是一个类的实例, 如:

boolean result = obj instanceof Class;

其中obj是对象,Class表示一个类或一个接口

obj为null时

System.out.println(null instanceof Object);//false

instanceof规则,当obj为null时,返回flase

子类与父类、接口间的比较

先准备四个类(接口)

interface Person{}

class Man implements Person{}

class Woman implements Person{}

class Worker extends Man{}

然后比较

public class Test
{
    public static void main(String args[]){
        Person pm = new Man();
        Person pwm = new Woman();
        Person pwo = new Worker();
        Worker wor = new Worker();
        
        //实现类与接口
        System.out.println(pm instanceof Person);//true
        //子类与父类
        System.out.println(pwo instanceof Man);//true
        //“隔代”实现类
        System.out.println(pwo instanceof Person);//true
        //没有继承关系
        System.out.println(pwo instanceof Woman);//false
        //没有向上转型的子类
        System.out.println(wor instanceof Person);//true
        //没有继承关系且没有向上转型
        System.out.println(wor instanceof Woman);//编译报错
    }
}

当obj不能转型成Class时,会编译报错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值