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".
3 points to say:
- LSP: a subtype can replace its parent type and the program stays correct.
- A subclass demands no more (preconditions), promises no less (postconditions), and keeps the parent's invariants.
- 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.