In my quest to write better, cleaner code, I am learning about SOLID principles. In this, LSP is proving to be little difficult to grasp properly.
My doubt is what if I have some extra methods in my subtype, S, which were not there in type, T, will this always be violation of LSP? If yes, then how do I extend
my classes?
For example, lets say we have a Bird
type. And its subtypes are Eagle
and Humming Bird
. Now both the subtypes have some common behavior as the Bird
. But Eagle
also has good predatory behaviour (which is not present in general Bird
type), that I want to use. Hence, now I won't be able to do this :
Bird bird = new Eagle();
So is giving Eagle
those extra behaviour breaking LSP ?
If yes, then that means I can't extend my classes because that would cause LSP violation?
class Eagle extends Bird {
//we are extending Bird since Eagle has some extra behavior also
}
Extending classes should be allowed in accordance with Open/Closed principle right?
Thank you in advance for answering ! As you can clearly see, LSP has got me confused like anything.
Edit: Refer this SO answer. In this again, when Car
has additional behaviour like ChangeGear
, it violates LSP. So, then how do we extend a class, without violating LSP?