Liskov Substitution Principle
The Liskov Substitution Principle (LSP) is a principle of object-oriented programming that states that if a program is using a class, it should be able to use any derived class of that class without knowing it, as long as the derived class follows the behavior of the base class.
In other words, the Liskov Substitution Principle allows derived classes to be used interchangeably with their base classes, as long as they follow the contract established by the base class.
Here is an example of a class that does not follow the Liskov Substitution Principle:
In this example, the Animal
class defines the core functionality (such as storing the animal's name), and the Bird
and Fish
classes add additional functionality (wingspan and fins) through inheritance. However, this design violates the Liskov Substitution Principle, because the Bird
and Fish
classes do not behave in the same way as the Animal
class. In particular, the Animal
class does not have a wingspan
or fins
attribute, so it is not possible to use a Bird
or Fish
object interchangeably with an Animal
object without knowing which specific type of object it is.
To fix this design and make it follow the Liskov Substitution Principle, we could add a wingspan
and fins
attribute to the Animal
class, or we could create a new base class for birds and fish that defines these attributes.
Here is an example of how we could modify the design to follow the Liskov Substitution Principle:
In this revised design, the Animal
class defines the core functionality (such as storing the animal's name, wingspan, and fins), and the Bird
and Fish
classes add additional functionality (specific types of wingspan and fins) through inheritance. This design follows the Liskov Substitution Principle, because we can use any of the derived classes interchangeably with the base Animal
class, as long as they follow the behavior of the base class.
Here is an example of how you could use the Animal
, Bird
, and Fish
classes interchangeably:
In this example, we create three animals: an Animal
object, a Bird
object, and a Fish
object. We then add them to a list and loop through the list, printing the name of each animal. Because the Animal
, Bird
, and Fish
classes follow the Liskov Substitution Principle, we can use them interchangeably without knowing which specific type of object they are.