java instanceof 报错_java instanceof方法

基本用法

null instanceof Object   为false; null instanceof 任意类 为false;

任意实例 instanceof 对应的类或者父类 都为true;

基本数据类型 instanceof Object 编译时会报错(如 int a;a instanceof Object 编译不通过),因为基本数据类型不是任何类的实例

instanceof与getClass的区别

public class Test

{

public static void testInstanceof(Object x)

{

System.out.println("x instanceof Parent: "+(x instanceof Parent));

System.out.println("x instanceof Child: "+(x instanceof Child));

System.out.println("x getClass Parent: "+(x.getClass() == Parent.class));

System.out.println("x getClass Child: "+(x.getClass() == Child.class));

}

public static void main(String[] args) {

testInstanceof(new Parent());

System.out.println("---------------------------");

testInstanceof(new Child());

}

}

class Parent {

}

class Child extends Parent {

}

/*

输出:

x instanceof Parent: true

x instanceof Child: false

x getClass Parent: true

x getClass Child: false

---------------------------

x instanceof Parent: true

x instanceof Child: true

x getClass Parent: false

x getClass Child: true

*/

从程序输出可以看出,instanceof进行类型检查规则是:你属于该类吗?或者你属于该类的派生类吗?而通过getClass获得类型信息采用==来进行检查是否相等的操作是严格的判断。不会存在继承方面的考虑

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值