Overriding without calling parent method, violating Liskov Principle

﹥>﹥吖頭↗ 提交于 2019-12-11 00:59:10

问题


I am developing a simple project. And I have a conflict with meaning of Liskov Principle in my project.

I simplified my question of my project with this example:

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())
    }
}

So, my question is, if I don't call parent method and write a completely new codes in override method, Is this violates Liskov Principle?

thanks.


回答1:


No, it will not violate the Liskov Principle as long as the subclass' implementation satisfies the expectations of the base class.




回答2:


LSP principle is about contracts when you have animal instance or get it from somebody and try to feed it you suppose that dog do what it should do instead of example fly away or trying to kill you. Proper dog implementation that fulfill Animal contract should fit to every place where expects Animal. When dog do something strange (something not in contract) it's violation of LSP. How exactly you implement methods of dog is not matter of context of LSP when they fulfill contracts.

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



来源:https://stackoverflow.com/questions/48046418/overriding-without-calling-parent-method-violating-liskov-principle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!