Liskov Substitution Principle
The Liskov substitution principle is one of the most important principles to adhere to in object-oriented programming (OOP).
It was introduced by the computer scientist Barbara Liskov in 1987 in a paper she co-authored with Jeannette Wing.
The principle states that child classes or subclasses must be substitutable for their parent classes or super classes.
In other words, the child class must be able to replace the parent class. This has the advantage of letting you know what to expect from your code.
Here’s an example of a code that does not violate the Liskov substitution principle:
The Dog
and Cat
classes can successfully replace the parent Animal
class.
On the other hand, let’s look at how the code below does violate the Liskov substitution principle:
The Bird
class violates the Liskov substitution principle because it’s not implementing its own makeSound
from the parent Animal
class. Instead, it’s inheriting the generic sound.
To fix this, you have to make it use the makeSound
method too:
Last updated