instanceof和getClass两种方法的区别

在比较一个类是否和另一个类属于同一个类实例的时候,我们通常可以采用instanceof和getClass两种方法通过两者是否相等来判断,但是两者在判断上面是有差别的,下面从代码中看看区别:

[java]  view plain  copy
  1. public class Test  
  2. {  
  3.     public static void testInstanceof(Object x)  
  4.     {  
  5.         System.out.println("x instanceof Parent:  "+(x instanceof Parent));  
  6.         System.out.println("x instanceof Child:  "+(x instanceof Child));  
  7.         System.out.println("x getClass Parent:  "+(x.getClass() == Parent.class));  
  8.         System.out.println("x getClass Child:  "+(x.getClass() == Child.class));  
  9.     }  
  10.     public static void main(String[] args) {  
  11.         testInstanceof(new Parent());  
  12.         System.out.println("---------------------------");  
  13.         testInstanceof(new Child());  
  14.     }  
  15. }  
  16. class Parent {  
  17.   
  18. }  
  19. class Child extends Parent {  
  20.   
  21. }  
  22. /* 
  23. 输出: 
  24. x instanceof Parent:  true 
  25. x instanceof Child:  false 
  26. x getClass Parent:  true 
  27. x getClass Child:  false 
  28. --------------------------- 
  29. x instanceof Parent:  true 
  30. x instanceof Child:  true 
  31. x getClass Parent:  false 
  32. x getClass Child:  true 
  33. */  
从程序输出可以看出,instanceof进行类型检查规则是:你属于该类吗?或者你属于该类的派生类吗?而通过getClass获得类型信息采用==来进行检查是否相等的操作是严格的判断。不会存在继承方面的考虑;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值