Substitutability: Liskov Substitution Principle
You'll learn why every subclass should be a reliable stand-in for its superclass without breaking expectations.
What Is the Liskov Substitution Principle?
The Liskov Substitution Principle (LSP) states that if class Dog extends class Animal, then anywhere in your code that expects an Animal, you should be able to pass a Dog without causing errors or unexpected behavior. This is the formal rule behind the is-a relationship you've already learned.
In plain English: a subclass must honor the "contract" of its superclass. It shouldn't:
- Break existing behavior
- Remove functionality
- Throw unexpected exceptions
- Change expected outcomes in surprising ways
A Real-World Analogy
Think of a universal remote control designed for any TV. If you buy a "SmartTV," it should still respond to the basic commands (power, volume, channel) just like a regular TV. If your SmartTV ignored the power button or made volume control turn the device off instead, it would violate the expectation—it wouldn't be substitutable for a regular TV.
Why This Matters
When you use a superclass reference (like Animal pet = new Dog();), you rely on the behavior promised by Animal. If Dog breaks those promises, code that worked with other animals will mysteriously fail with dogs. This undermines the entire purpose of inheritance and type compatibility.
Good inheritance respects substitutability. Bad inheritance creates surprising bugs when subclasses behave unpredictably.
Key Takeaway:
A subclass must work correctly wherever its superclass is expected—this is the Liskov Substitution Principle, the foundation of safe, predictable inheritance.