Liskov Substitution Principle | SOLID Principles

In this post, I am going to discuss the third design principle of SOLID, which is the Liskov Substitution Principle.

The SOLID principles are a set of five principles for object-oriented class design. These best practices and rules should be followed when designing a class.

The SOLID acronym stands for –

S – Single Responsibility Principle

O – Open/Closed Principle

L – Liskov Substitution Principle

I – Interface Segregation Principle

D – Dependency Inversion Principle

Liskov Substitution Principle (LSP)

Liskov substitution principle states that the objects of a superclass should be replaceable with objects of its subclasses without breaking the application.

In other words, subtypes must be substitutable for their base types.

Example 1

To understand this let’s take an example –

In the above code example, class B is a child class of A. As per Liksov substitution principle, we should be able to replace objects of A with Objects of B without changing it’s behavior (correctness, functionality etc.) of our program.

A child class should never change the characteristics of it’s parent class.

Example 2

Let’s take an example of a Rectangle class. In a Rectangle, we know that two parallel sides are equal to each other. So, it has two properties: width and height.

Let’s me create another class Square which is extending Rectangle class. So, there exists IS-A relationship. Square IS-A rectangle. We all know square has all it’s side equal.

Our Square class extends Rectangle, but it modifies the expected behavior of Rectangle, which violates LSP.

How to Fix the LSP Voilation

To fix this problem we can use composition instead of inheritance.

Inheritance Vs Composition in Java

Important Points –

1. LSP applicable where there is supertype-subtype relationship. Either by extending a class or implementing an interface.

2. We need to make sure that new derived classes are extending the base classes without changing their original behavior.

3. If a subtype of the supertype does something that the client of the supertype does not expect, then this is the violation of LSP.

Liskov Substitution Principle Video Tutorial

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.