[Java] instanceof & getClass

有兩個方法可以得到物件的型別

  1. instanceof,除了可以得到物件的型別,也可以得到物件的繼承關係。
  2. getClass搭配equals,只能判斷物件與類別的直接關係,不能判斷物件的繼承關係。

可以參考下方例子會更清楚。


Cat類別繼承Animal類別,而Airplane實作Flyer介面

public class Test {

    public static void main(String[] args) {
        Cat cat = new Cat();
        Airplane airplane = new Airplane();
        
        // instanceof
        if (cat instanceof Animal) {
            System.out.println("cat is Animal class");
        }
        if (cat instanceof Cat) {
            System.out.println("cat is Cat class");
        }
        
        System.out.println("========================");
        
        
        // getClass
        if (cat.getClass().equals(Animal.class)) {
            System.out.println("cat is Animal class");
        }
        if (cat.getClass().equals(Cat.class)) {
            System.out.println("cat is Cat class");
        }
        
        System.out.println("========================");
        
        
        if (cat.getClass().equals(Airplane.class)) {
            System.out.println("cat is Dog class");
        } else {
            System.out.println("cat is not Dog class");
        }
        
        System.out.println("========================");
        
        
        if (airplane instanceof Airplane) {
            System.out.println("airplane is Airplane class");
        }      
        if (airplane instanceof Flyer) {
            System.out.println("airplane is Flyer class");
        }
        
        System.out.println("========================");
        
        
        if (airplane.getClass().equals(Airplane.class)) {
            System.out.println("airplane is Airplane class");
        }
        
        if (airplane.getClass().equals(Flyer.class)) {
            System.out.println("airplane is Flyer class");
        }

    }
}

 

輸出

cat is Animal class
cat is Cat class
========================
cat is Cat class
========================
cat is not Dog class
========================
airplane is Airplane class
airplane is Flyer class
========================
airplane is Airplane class

 

使用instanceof,除了可以得知cat物件屬於Cat類別,也可判斷出cat物件與Animal類別有某種繼承關係。

使用instanceof,也可知道物件與實作類別的關係,像是例子中能知道airplane與Flyer類別有某種繼承或實作關係

使用getClass搭配equals,只能判斷cat物件屬於Cat類別,不能判斷出cat物件與Animal類別有關係

 

下方為使用instanceof練習寫判斷物件型別的方法

private static void judgeClassByInstanceOf(Object o) {
    if (o instanceof String) {
        System.out.println(o + " is String type");
    } else if (o instanceof Float) {
        System.out.println(o + " is Float type");
    } else if (o instanceof Double) {
        System.out.println(o + " is Double type");
    } else if (o instanceof Integer) {
        System.out.println(o + " is Integer type");
    } else if (o instanceof Boolean) {
        System.out.println(o + " is Boolean type");
    }
}