SteelReed

Search

Search posts, questions…

OOP & DesignQuestion 12 / 42

Middle

What is Liskov Substitution? Why is Square extends Rectangle wrong, and what are other violations?

Short answer

LSP: anywhere the parent type is used, the subtype must work and the program stay correct. "Is-a" in math (a square is a rectangle) is not the same as "substitutable in behavior".

real Rectangleactually a SquareCode using RectanglesetWidth 5, setHeight 4Area 20: correctArea 16: broken

3 points to say:

  1. LSP: a subtype can replace its parent type and the program stays correct.
  2. A subclass demands no more (preconditions), promises no less (postconditions), and keeps the parent's invariants.
  3. Square/Rectangle breaks with setters, works when immutable; fix with split interfaces, composition, contract tests.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.