zoukankan      html  css  js  c++  java
  • java-----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获得类型信息采用==来进行检查是否相等的操作是严格的判断。不会存在继承方面的考虑;

  • 相关阅读:
    2020 11 21
    2020 11 20
    2020 11 19
    2020 11 18
    2020 11 17
    2020 11 16
    2020 11 15
    2020 11 14
    2020 11 14
    第五周学习进度报告
  • 原文地址:https://www.cnblogs.com/diegodu/p/7266953.html
Copyright © 2011-2022 走看看