SOLID Principles • Liskov Substitution PrincipleEasy⏱️ ~2 min
What is the Liskov Substitution Principle?
Definition
Liskov Substitution Principle (LSP) states that objects of a superclass should be replaceable with objects of its subclasses without breaking the application. If class B is a subtype of class A, then we should be able to replace A with B without disrupting the behavior of the program.
Named after computer scientist Barbara Liskov, LSP is the L in SOLID principles. It ensures that inheritance is used correctly by maintaining behavioral compatibility between parent and child classes.
Problem it Solves
Without LSP, inheritance hierarchies become fragile and unpredictable. Client code that works with base classes might break when subclasses are introduced, forcing developers to check types and add special cases. This violates the Open-Closed Principle (OCP) and makes code difficult to extend.
Core Requirements
For a subclass to satisfy LSP, it must preserve:
- Preconditions: Cannot be strengthened. If the parent accepts null, the child cannot reject it.
- Postconditions: Cannot be weakened. If parent guarantees non-null return, child must too.
- Invariants: Must be preserved. Properties true for parent must remain true for child.
- History constraint: Child cannot modify immutable properties of parent.
Interview Tip: LSP is about behavioral compatibility, not just structural inheritance. A square mathematically "is-a" rectangle, but in object-oriented design,
Square often violates LSP when inheriting from Rectangle because it restricts behavior (width and height must be equal).💡 Key Takeaways
✓Subtypes must be substitutable for their base types without altering program correctness
✓LSP ensures behavioral compatibility, not just structural inheritance
✓Violations force client code to check types and add special cases
✓Maintains the contract established by the parent class
✓Critical for polymorphism to work correctly in real applications
📌 Examples
1Rectangle-Square problem: Square restricts Rectangle behavior, violating LSP
2Bird-Penguin hierarchy: If Bird has fly(), Penguin violates LSP as it cannot fly