Java學習3-一個類既有父類又實現了接口,那它是什麼類型

Java學習3-一個類既有父類又實現了接口,那它是什麼類型

 

一個類通常會出現繼承了一個類,然後還實現了接口,這個情況在Spring的源碼中非常常見。那麼這個類到底是什麼類型呢?

這個問題其實就是分別屬於兩中類型,我覺得這就是多態的一種表現。下面就用一個小例子來驗證下。

Cat類是Animal的一個子類,但是實現了Pet寵物類這個接口。

public class Cat extends Animal implements Pet{

    private String color;


    public void print(){
        System.out.println("sub class");
    }

    public Cat(String name,Integer age,String color) throws Exception{
//        super(name,age);
//        System.out.println(super.getName()+"--------"+super.getClass().getField("color"));
        this.color = color;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

下面是測試方法

  @Test
    public void testMultipleType() throws Exception{

        Cat cat = new Cat("aa",12,"red");

        if(cat instanceof Animal){
            System.out.println("is animal");
        }
        if(cat instanceof Pet){
            System.out.println("is pet ");
        }

    }

輸出結果

/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/bin/java -ea -
is animal
is pet 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章