码迷,mamicode.com
首页 > 编程语言 > 详细

java-----instanceof与getClass的区别

时间:2017-08-01 10:16:39      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:oar   start   too   派生   getc   rgs   eof   tail   alt   

在比较一个类是否和另一个类属于同一个类实例的时候,我们通常可以采用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获得类型信息采用==来进行检查是否相等的操作是严格的判断。不会存在继承方面的考虑;

java-----instanceof与getClass的区别

标签:oar   start   too   派生   getc   rgs   eof   tail   alt   

原文地址:http://www.cnblogs.com/diegodu/p/7266953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!