Skip to content
Low Level Design Mastery Logo
LowLevelDesign Mastery

Liskov Substitution Principle

Subtypes must be substitutable for their base types without breaking the program.

The Liskov Substitution Principle (LSP) states that objects of a superclass should be replaceable with objects of its subclasses without breaking the application. In other words, derived classes must be substitutable for their base classes.

This principle was introduced by Barbara Liskov in 1987 and is a fundamental concept in object-oriented design.

Diagram

The Liskov Substitution Principle ensures that:

  • Subclasses must honor the contract of their base class
  • Subclasses should not weaken preconditions (requirements before a method runs)
  • Subclasses should not strengthen postconditions (guarantees after a method runs)
  • Subclasses should not throw new exceptions that the base class doesn’t throw

In simple terms: If it looks like a duck and quacks like a duck, it should behave like a duck!

This is a classic example that demonstrates LSP violation. Let’s see why a Square should NOT inherit from Rectangle.

Diagram
Diagram

Why this follows LSP:

  • Both Rectangle and Square honor the Shape contract
  • They can be used interchangeably where Shape is expected
  • No unexpected behavior changes

Consider a payment processing system where different payment methods need to be processed. Let’s see how LSP violations can cause real-world problems.

Diagram

Why this violates LSP:

  • Code expecting PaymentProcessor breaks with CryptocurrencyProcessor
  • refund() should always work, but crypto version throws exception
  • The contract is broken: refunds should be possible for all payment types
Diagram

Why this follows LSP:

  • Each class honors its specific contract
  • CryptocurrencyProcessor doesn’t promise refunds it can’t deliver
  • Type system prevents using non-refundable processors where refunds are needed
  • No unexpected behavior or exceptions


Remember: The Liskov Substitution Principle ensures that inheritance is used correctly and polymorphism works as expected! 🎯

💡 Time to Practice!

Now that you understand the concepts, put them into practice with our interactive playground. Build UML diagrams, write code, and get AI-powered feedback.

Browse All Problems