0% completed
The Liskov Substitution Principle (LSP) is an important concept in object-oriented design. It states:
"Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program."
This principle means that a subclass should behave in a way that it can substitute for its parent class without causing issues in the system. If a subclass breaks the behavior expected from the parent class, it violates LSP.
Problem Example: Car and Electric Car
Let’s take a simple example of a Car class to see where the problem arises when LSP is violated.
- Imagine you have a
Car
class with methods to start, stop, and refuel the car. - Now, you decide to extend this class and create an
ElectricCar
class. This class should also start and stop like a regular car, but since it doesn’t use fuel, therefuel()
method becomes problematic. - Instead
ElectricCar
class hasrecharge()
method.
In this example, the ElectricCar
class overrides the refuel()
method from the Car
class, but it cannot implement the functionality properly because electric cars don’t use fuel. This leads to an issue where calling the refuel()
method on an ElectricCar
will break the program by throwing an exception.
Why Previous Example Violates LSP?
According to the Liskov Substitution Principle, we should be able to replace an instance of Car
with an instance of ElectricCar
without breaking the functionality. However, let’s see what happens when we create objects of these classes and call their methods.
In this example:
-
We create an instance of the
Car
class and everything works as expected. -
We then create an instance of the
ElectricCar
class, but treat it as aCar
(sinceElectricCar
is a subclass ofCar
). -
When we call the
refuel()
method on theElectricCar
object, it throws anUnsupportedOperationException
because electric cars don’t use fuel. This breaks the program.
The Actual Reason Behind the Violation of LSP
This behavior violates the Liskov Substitution Principle because:
- We cannot seamlessly substitute an instance of the
Car
class with an instance ofElectricCar
without breaking the program. - The
ElectricCar
class cannot fulfill the contract of theCar
class, specifically regarding therefuel()
method.
In this lesson, we’ve seen how trying to treat ElectricCar
as a Car
leads to issues when the expected behavior of the parent class isn’t respected by the subclass. In the next lesson, we will explore how to properly redesign the system to adhere to LSP.
.....
.....
.....
On this page
Problem Example: Car and Electric Car
Why Previous Example Violates LSP?
The Actual Reason Behind the Violation of LSP