instanceof的用法(java)

java 中的instanceof 是一个二元操作符(运算符)运算符,由于是字母组成,所以是Java的保留关键字,但是和>=,<=,==属同一类,它的作用是用来判断,instanceof 左边对象是否为instanceof 右边类的实例,返回一个boolean类型值。还可以用来判断子父类的所属关系。

语法:

boolean result = object instanceof Class
需要注意的是,如果object为null返回的是false。

test:

public interface Human {

}

public class Person implements Human{

}

public class Boy extends Person {
 }

 

public class Demo {
    
    public static void main(String[] args) {
        Boy boy = new Boy();
        Boy boy2 = null;
        Person person = new Person();
        Person person2 = new Boy();

        System.out.println(boy instanceof Person);//true
        System.out.println(boy instanceof Human);//true
        System.out.println(boy instanceof Boy);     //true

        System.out.println("=======");
        System.out.println(boy2 instanceof Person);//false
        System.out.println(boy2 instanceof Human);//false
        System.out.println(boy2 instanceof Boy);     //false
        System.out.println("=======");
        System.out.println(person instanceof Boy);//false
        System.out.println(person instanceof Human);//true
        System.out.println(person instanceof Person);//true

        System.out.println("=======");
        System.out.println(person2 instanceof Boy);//true
        System.out.println(person2 instanceof Human);//true
        System.out.println(person2 instanceof Person);//true
 
    }

输出的结果:

true
true
true
=======
false
false
false
=======
false
true
true
=======
true
true
true
 

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值