What’s the Liskov Substitution Principle?

Get a brief introduction to the Liskov substitution principle.

The Liskov substitution principle was initially introduced by Barbara Liskov, an American computer scientist, in 1987. The principle states that if you substitute a parent with any of its derived classes, the behavior of the program shouldn’t change.

This principle was introduced specifically with inheritance in mind, which is an integral feature of object-oriented programming. Inheritance allows us to extend the functionality of classes or modules (depending on what programming language we use). So, if we need a class with some new functionality that’s closely related to what we already have in a different class, we can just inherit it from the existing class instead of creating a completely new one.

When inheritance is applied, any object-oriented programming language will allow us to insert an object that has the derived class as its data type into a variable or parameter that expects an object of the parent class. For example, if we had a Car named base class, we could create another SportsCar named class that inherits from it. In this case, an instance of SportsCar is also an instance of the Car class, just like it would’ve been in real life. Therefore, a variable or parameter that’s of the type Car would be able to be set to an instance of the SportsCar class.

And this is where a potential problem arises. There might be a method or a property inside the original Car class that uses some specific behavior, and other places in the code have been written to expect that specific behavior from the instances of Car objects. However, inheritance allows those behaviors to be completely overridden.

If the derived class overrides some of the properties and methods of the parent class and modifies their behavior, then passing an instance of the derived class into the places that expect the parent class might cause unintended consequences. This is exactly the problem that the Liskov substitution principle was designed to address.

Get hands-on with 1200+ tech skills courses.