What is LSP (Liskov Substitution Principle) and what are some examples of its use (good and bad)?

Technology CommunityCategory: OOPWhat is LSP (Liskov Substitution Principle) and what are some examples of its use (good and bad)?
VietMX Staff asked 3 years ago

The Liskov Substitution Principle (LSP, lsp) is a concept in Object Oriented Programming that states:

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. IN other words 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.

Consider the bad example:

public class Bird{
    public void fly(){}
}
public class Duck extends Bird{}
public class Ostrich extends Bird{}

The duck can fly because of it is a bird. Ostrich is a bird, but it can’t fly, Ostrich class is a subtype of class Bird, but it can’t use the fly method, that means that we are breaking LSP principle.

So the right example:

public class Bird{
}
public class FlyingBirds extends Bird{
    public void fly(){}
}
public class Duck extends FlyingBirds{}
public class Ostrich extends Bird{}