不调用父方法就重写,违反里氏原则

Overriding without calling parent method, violating Liskov Principle

我正在开发一个简单的项目。而且我在项目中与里氏原理的含义有冲突。

我用这个例子简化了我的项目问题:

public class Animal {  

     public void feed() {     

         // do something here         
     }    
}    


public class Dog extends Animal {

    // some methods and attributes

    @Override
    public void feed() {   

        // never call parent feed() method (super.feed())
    }
}

所以,我的问题是,如果我不调用parent方法,在override方法中写一个全新的代码,这是否违反了Liskov Principle?

谢谢。

不会,只要subclass'实现满足基class的期望,就不会违反里氏原则。

LSP 原则是关于合同的,当你有动物实例或从某人那里得到它并试图喂它时,你假设狗会做它应该做的事,而不是例子飞走或试图杀死你。履行 Animal 合同的正确 dog 实施应该适合每个需要 Animal 的地方。当狗做一些奇怪的事情(不符合合同的事情)时,它违反了 LSP。当 LSP 履行合同时,你如何准确地实现 dog 的方法与 LSP 的上下文无关。

Substitutability is a principle in object-oriented programming stating that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e. an object of type T may be substituted with any object of a subtype S) without altering any of the desirable properties of T (correctness, task performed, etc.).

https://en.wikipedia.org/wiki/Liskov_substitution_principle