2.3.3、里氏替换原则

里氏替换原则 Liskov Substitution Principle(LSP)

定义

如果对每一个类型为S的对象o1,都有类型为T的对象o2,使得以T定义的所有程序P在所有的对象o1都代换成o2时,程序P的行为没有发生变化,那么类型S是类型T的子类型。 If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T,the behavior of P is unchanged when o1 is substituted for o2 then S is a sub type of T.

所有引用基类的地方必须能透明地使用其子类的对象。Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

里氏替换原则通俗的来讲就是:子类可以扩展父类的功能,但不能改变父类原有的功能。

其实这个原则我们平时都是遵守,只要子类不重写父类的方法。但是有几种情况可能会有不自觉的违反里氏替换原则

我们先创建一个鸟的基类

public class BaseBird {
    protected void fly()
    {
        Log.e("ldy","会飞");
    }
    protected void running()
    {
        Log.e("ldy","会跑");
    }
}

 鸵鸟子类去继承这个鸟类

public class Ostrich extends BaseBird{
//1、子类和父类的方法重名
    public void running()
    {
        Log.e("ldy","跑的很快");
    }
//2、重写父类fly方法
    @Override
    public void fly()
    {
        Log.e("ldy","不会飞");
    }
}

1、子类和父类的方法不小心重名了,导致Ostrich .running从会跑,变成跑的很快。修改了父类的功能,不符合里式替换。

2、因为鸟的基类定义错了,并不是所有鸟都会飞,所以不得不重写fly方法,不符合里式替换。

扫描二维码关注公众号,回复: 8987244 查看本文章
发布了39 篇原创文章 · 获赞 2 · 访问量 5006

猜你喜欢

转载自blog.csdn.net/u013636987/article/details/104160402