里氏替換原則(Liskov Substitution Principle LSP)

Liskov於1987年提出了一個關於繼承的原則“Inheritance should ensure that any property proved about supertype objects also holds for subtype objects.”——“繼承必須確保超類所擁有的性質在子類中仍然成立。”也就是說,當一個子類的實例應該能夠替換任何其超類的實例時,它們之間才具有is-A關係。

這裏寫圖片描述

public abstract class AbstractBird {

    protected String color;
    protected String name;

    public AbstractBird(String color, String name) {
        this.color = color;
        this.name = name;
    }

    public void show() {
        System.out.println("看那是" + this.name + ":顏色是" + this.color);
        drinking();
        goWalk();
        sleep();
    }

    public abstract void goWalk();

    public abstract void sleep();

    public abstract void drinking();
}

public class Zoo {

    private AbstractBird abstractBird;

    public Zoo(AbstractBird abstractBird) {
        this.abstractBird = abstractBird;
    }

    public void show() {
        this.abstractBird.drinking();
    }
}
    public static void main(String[] args) {
//      Zoo zoo = new Zoo(new Canary("紅色", "金絲雀"));
        Zoo zoo = new Zoo(new Magpie("藍色", "喜鵲"));
//      Zoo zoo = new Zoo(new Sparrow("黑色","麻雀"));
        zoo.show();

對象本身有一套對自身狀態進行校驗的檢查條件,以確保該對象的本質不發生改變,這稱之爲不變式(Invariant)。

public class Stone {

    public Number getNumber() {
        return new Integer(99);
    }
}

public class Adamas extends Stone {

    @Override
    public Integer getNumber(){
        return new Integer(22);
    }
}
public class StoneClient {

    public static void main(String[] args) {
        Stone stone = new Adamas();
        System.out.println(stone.getNumber());
    }
}
答案
22

如果把父類的參數縮小,子類的參數擴大,就問題出問題

public class Stone {

    public Number getNumber(HashMap map) {
        return new Integer(99);
    }
}
public class Adamas extends Stone {

    public Number getNumber(Map map) {
        return new Integer(22);
    }
}
public class StoneClient {

    public static void main(String[] args) {
        //Stone stone = new Stone();
        Adamas stone = new Adamas();
        System.out.println(stone.getNumber(new HashMap()));
    }
}
答案 2個打印出都是99 ,我們想要的,9922

總結就是子類的方法參數一定要小於等於父類的參數。

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