Overriding without calling parent method, violatin

2019-07-24 03:48发布

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.

2条回答
Melony?
2楼-- · 2019-07-24 04:24

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

查看更多
萌系小妹纸
3楼-- · 2019-07-24 04:32

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

查看更多
登录 后发表回答