1.instanceof isInstanceof考虑的继承关系。指你是这个类吗?你是这个类的派生类吗?(后者需要通过class对象 去比较)

    1. public class FamilyVsExacType {
    2. static void test(Object o){
    3. //instanceof 和isInstanceof考虑的继承关系。
    4. System.out.println("o.getClass"+o.getClass());
    5. System.out.println("o instanceof Base "+(o instanceof Base));
    6. System.out.println("o instanceof Dirved "+(o instanceof Drived));
    7. System.out.println("Base.isInstanceof(o) "+(Base.class.isInstance(o)));
    8. System.out.println("Drived.isInstanceof(o) "+(Drived.class.isInstance(o)));
    9. System.out.println("================================");
    10. }
    11. public static void main(String[] args) {
    12. test(new Drived());
    13. System.out.println();
    14. test(new Base());
    15. }
    16. Output:
    17. o.getClassclass com.package14.Two.Drived
    18. o instanceof Base true
    19. o instanceof Dirved true
    20. Base.isInstanceof(o) true
    21. Drived.isInstanceof(o) true
    22. o.getClassclass com.package14.Two.Base
    23. o instanceof Base true
    24. o instanceof Dirved false
    25. Base.isInstanceof(o) true
    26. Drived.isInstanceof(o) false



    **
    2.==和equals在比较Class对象时只比较具体的值不考虑继承关系,_**

    1. ublic class FamilyVsExacType {
    2. static void test(Object o){
    3. //==和equals只比较具体的值不考虑继承关系
    4. System.out.println("o.class==Base.class "+(o.getClass()==Base.class));
    5. System.out.println("o.class==Drived.class "+(o.getClass()==Drived.class));
    6. System.out.println("o.getClass.equals(Base.class) "+(o.getClass().equals(Base.class)));
    7. System.out.println("o.getClass.equals(Dirved.class) "+(o.getClass().equals(Drived.class)));
    8. }
    9. public static void main(String[] args) {
    10. test(new Drived());
    11. System.out.println();
    12. test(new Base());
    13. }
    14. OutPut:
    15. o.class==Base.class false
    16. o.class==Drived.class true
    17. o.getClass.equals(Base.class) false
    18. o.getClass.equals(Dirved.class) true
    19. ================================
    20. o.class==Base.class true
    21. o.class==Drived.class false
    22. o.getClass.equals(Base.class) true
    23. o.getClass.equals(Dirved.class) false

    注意:同一类的不同实列的Class对象相同(每一个类有一个Class对象)

    1. Base base = new Base();
    2. Base base2 = new Base();
    3. //同一个类的实例的Class对象指向同一个Class对象
    4. Class<? extends Base> aClass = base.getClass();
    5. Class<? extends Base> aClass1 = base2.getClass();
    6. System.out.println(aClass1==aClass1);
    7. output:
    8. true