The Rectangle-Square Problem
What you'll learn: You'll see the most famous example of how violating LSP creates subtle bugs when a Square inherits from Rectangle.
The Classic Violation
Mathematically, every square is a rectangle. So it seems natural to make Square inherit from Rectangle, right? Wrong—this creates a textbook LSP violation.
Imagine a Rectangle class with setWidth() and setHeight() methods that work independently. Code using a Rectangle expects to set width to 5 and height to 10 and get a 5×10 rectangle.
Now introduce Square, which inherits from Rectangle. But squares must keep width and height equal! So when you call setWidth(5) on a Square, it must also change the height to 5 to maintain the square constraint.
Why This Breaks Substitution
Any code that works with a Rectangle now breaks when you pass a Square:
function resizeRectangle(rect):
rect.setWidth(5)
rect.setHeight(10)
assert rect.area == 50 // Fails if rect is actually a Square!
The Square violated the Rectangle's behavioral contract: that width and height can be set independently. The function didn't modify its preconditions or postconditions—it just expected normal Rectangle behavior. But substituting a Square broke everything.
This demonstrates behavioral subtyping: inheritance should preserve parent class behavior expectations, not just share code. A true subtype must honor all assumptions clients make about the parent type.
The Solution
Don't force inheritance based purely on "is-a" relationships in the real world. Instead, use interfaces or redesign your hierarchy so both Rectangle and Square inherit from a common Shape abstraction without inherited mutability.
Key Takeaway: The Rectangle-Square problem shows that mathematical or real-world "is-a" relationships don't always translate to valid inheritance—subtypes must preserve behavioral contracts, not just structural similarities.