2021-04-17

Java关键字用法

instanceof
  • instanceof是java的一个双目运算符
 boolean result = obj instanceof Class
 obj表示一个对象
 Class表示一个类或者一个接口
 当obj是Class的对象,或者是其直接或间接的子类的对象,或者是其接口的实现类,均返回true
  • obj必须是引用类型,不能是基本类型
int i = 1;
System.out.println(i instanceof Integer); //编译不通过
System.out.println(i instanceof Object);  //编译不通过
  • objnull
如果 obj 为 null,那么将返回 false
System.out.println(null instanceof Integer);  //输出false
  • obj为Class接口的实现类的对象
ArrayList arrayList = new ArrayList();
System.out.println(arrayList instanceof List); //输出 true

List list = new ArrayList();
System.out.println(list instanceof ArrayList); //输出 true
  • obj为Class的子类或间接子类的对象
public class Main2 {
    public static void main(String[] args) {
        Person2 p1 = new Person2();
        Person2 p2 = new student2();
        student2 s1 = new student2();

        System.out.println(p1 instanceof Person2);   //输出true
        System.out.println(p2 instanceof Person2);   //输出true
        System.out.println(p2 instanceof student2);  //输出true
        System.out.println(s1 instanceof Person2);   //输出true
        System.out.println(p1 instanceof student2);  //输出false

    }
}

class Person2{

}

class student2 extends Person2{

}
  • instanceof无法通过编译和返回false
pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值