Square extends Rectangle, and set_width() on a square also changes its height. Code that sets width=2, height=5 and expects area 10 breaks. Which principle is violated?
Options
- Single Responsibility
- Liskov Substitution (Correct option)
- Interface Segregation
- Dependency Inversion
Answer
Liskov Substitution
Why
Liskov Substitution says: anywhere the code expects a parent class, you must be able to give it a child class without breaking anything.
Code written for Rectangle assumes width and height change independently. A Square breaks that assumption, so it is not a safe substitute even though 'a square is a rectangle' in math.
Fix: make them separate shapes (or immutable).
Remember
A subclass must keep every promise its parent makes.