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.

Deep dive: Design Patterns, Explained Simply: SOLID, Part 2

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

← All Design Patterns questions