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

  • 相关阅读:
    P2639 [USACO09OCT]Bessie的体重问题Bessie's We…
    P2871 [USACO07DEC]手链Charm Bracelet
    P1983 车站分级
    P1038 神经网络
    P1991 无线通讯网
    P1546 最短网络 Agri-Net
    P1197 [JSOI2008]星球大战
    P1004 方格取数
    P1111 修复公路
    pd_ds 之 hash
  • 原文地址:https://www.cnblogs.com/diegodu/p/7266953.html
Copyright © 2011-2022 走看看