LSP (Liskov Substitution Principle) — Explained with Examples
The Liskov Substitution Principle states that objects of a superclass should be replaceable with objects of a subclass without affecting program correctness.
LSP stands for Liskov Substitution Principle, the third of the five SOLID principles. Barbara Liskov introduced it in 1987: “If S is a subtype of T, then objects of type T may be replaced with objects of type S without altering any of the desirable properties of the program.”
Why LSP Matters
Violating LSP breaks polymorphism — one of the core benefits of object-oriented programming. When subclasses behave unexpectedly differently from their parent, code that relies on the base type breaks at runtime. Following LSP ensures your inheritance hierarchies are logically sound.
Real-World Analogy
If a restaurant menu says “drink” and you can get water, soda, or juice — all of them satisfy “drink.” But if “drink” sometimes gives you a hamburger, the menu contract is broken. LSP ensures subclasses honor the contract defined by the parent class.
Example: Violating LSP
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def set_width(self, w):
self.width = w
def set_height(self, h):
self.height = h
def area(self):
return self.width * self.height
class Square(Rectangle):
def __init__(self, size):
super().__init__(size, size)
def set_width(self, w):
self.width = w
self.height = w # violates LSP — changes height too
def set_height(self, h):
self.height = h
self.width = h # violates LSP — changes width too
# Code expecting a Rectangle breaks with Square
def increase_rectangle_width(rect):
rect.set_width(rect.width + 1)
# Expects height unchanged, but Square changes both
# Fix: Use composition or a common Shape interface
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Square(Shape):
def __init__(self, size):
self.size = size
def area(self):
return self.size ** 2Related Terms
SOLID, Encapsulation, Composition over Inheritance, Polymorphism
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro