Design Patterns interview question · Most asked
Explain the Liskov Substitution Principle with an example.
Summary
Subtypes must be usable wherever their parent type is expected, without breaking the parent's promises. The classic violation: Square extends Rectangle, where setting the height also changes the width, so code expecting area 5 x 4 = 20 gets 16.
Longer Answer
LSP is about behavioural compatibility, not vocabulary. A square "is a" rectangle in geometry, but not a correct subtype of a mutable Rectangle class whose contract says width and height change independently.
Signs of violations: overridden methods that throw "not supported", stricter preconditions, weaker results, and callers that need instanceof checks. Fixes include modelling by shared behaviour (an immutable Shape with area()), or composition instead of inheritance.
Key Points
- Subtypes must keep the parent's contract.
- Square/Rectangle is the classic violation.
- Smells: 'not supported' overrides, instanceof checks.
- Fix by modelling shared behaviour or composing.
Explanation
What interviewers look for
A correct example and the idea of contracts (preconditions, postconditions), not just 'subclasses can replace parents'.
Follow-up questions
- How would you redesign Square and Rectangle?
- How does LSP relate to unit tests written against an interface?
More most-asked Design Patterns questions
- What is a design pattern, and why are they useful?
- Explain the SOLID principles.
- What is the difference between dependency inversion, dependency injection and inversion of control?
- Why is composition often preferred over inheritance?
- What is dependency injection, and what forms does it take?
- Explain the Factory Method pattern and how it differs from a simple factory.
- What problem does the Builder pattern solve? Show an example.
- How do you implement a Singleton, and why is it often considered an anti-pattern?