Liskov Substitution Principle

Suyash Upadhyay
Design Patterns & Principles
3 min readJan 14, 2022

The Liskov Substitution Principle (LSP) is one of five SOLID object-oriented design principles defined by Barbara Liskov.

The principle defines that objects of a superclass shall be replaceable/interchangeable with objects of its subclasses without breaking the application. That requires the objects of your subclasses to behave in the same way as the objects of your superclass.

Let us see, by an example:

As I am a huge fan of Head First Series Books, my examples are quite motivated by the examples mentioned there.

Let us take a class name Bird, having two behaviors: display(), and fly()

Bird bird = new Bird();

and a subclass name Penguins and Pigeons of super class Bird.

Here the objects of the Bird (super) class is replaceable by the object of the sub class Pigeons, but the same principle is not good with the case of sub class Penguins, as we know that Penguins cant fly..

From the compiler’s point of view, It is Ok to use instance of Penguin in place of Bird, But when you will start to actually use the instance of Penguin like a Bird, things will start creating confusion.

Violation of LSP will significantly impact the understanding of your code as it misuses the concept of inheritance.

Let’s now look at some techniques that we can follow and use to ensure we create well-behaved subtypes.

Rule 1. Method Argument Types
The subtype method argument types can be identical or wider than the super type method argument types.

Java’s method overriding rules support this rule by enforcing that the overridden method argument types match exactly with the super type method.

Rule 2. Return Types
The return type of the subtype method can be narrower than the return type of the super type method. This is called covariance of the return types. Covariance indicates when a subtype is accepted in place of a super type. Java supports the covariance of return types.

Rule 3. Exceptions
The subtype method can throw fewer or narrower (but not any additional or broader) exceptions than the super type method.
Java’s method overriding rules already enforce this rule for checked exceptions.

Summary

The Liskov Substitution Principle is the third of Robert C. Martin’s SOLID design principles. It enables you to replace objects of a parent class with objects of a subclass without breaking the application.

Before Ending, a hint for the right way to solve our Bird Flying problem, without using inheritance.

Credit: Head First Object-Oriented Analysis & Design

--

--