What is the Liskov Substitution Principle
You'll learn: What LSP means and why subclasses must be true substitutes for their parent classes.
The Liskov Substitution Principle (LSP) is the "L" in SOLID. It states that objects of a superclass should be replaceable with objects of a subclass without breaking the application. In other words, if you have code that works with a parent class, it should work equally well with any of its child classes—no surprises, no unexpected errors.
The Core Idea
Imagine you own a car. You expect all cars to accelerate when you press the gas pedal. Now suppose someone gives you a special "SafetyCar" subclass that refuses to accelerate above 20 mph, even when you floor it. Technically it's still a car, but it violates your expectations. Code that assumes normal car behavior would break or behave incorrectly with this SafetyCar.
LSP says: a subclass must honor the contract established by its parent class. This means:
- It shouldn't strengthen preconditions (require more than the parent)
- It shouldn't weaken postconditions (promise less than the parent)
- It shouldn't throw unexpected exceptions
- It shouldn't change expected behavior in surprising ways
Why It Matters
When subclasses violate LSP, you can't trust polymorphism. You end up writing defensive checks like "if this is actually a SafetyCar, do something different"—defeating the purpose of inheritance and abstraction. LSP ensures that your inheritance hierarchies are logically correct, not just syntactically valid.
LSP works hand-in-hand with the Open/Closed Principle you just learned: you can extend behavior through subclasses, but those subclasses must be genuine, trustworthy replacements.
Key Takeaway: The Liskov Substitution Principle ensures subclasses can replace their parent classes without breaking code—honoring the parent's contract and maintaining expected behavior.