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

  • 相关阅读:
    过渡效果
    生命周期
    事件处理
    列表的搜索和排序
    DotNetBar for Windows Forms 12.1.0.0_冰河之刃重打包版 原创发布
    DotNetBar for Windows Forms 11.8.0.8冰河之刃重打包版
    闲读
    POJ 3253 Fence Repair 贪心 优先级队列
    POJ 2431 Expedition 贪心 优先级队列
    优先级队列-堆-STL实现
  • 原文地址:https://www.cnblogs.com/diegodu/p/7266953.html
Copyright © 2020-2023  润新知