Concept · Core

Liskov Substitution (L)

A subclass must be usable ANYWHERE its parent is, without surprising the caller. If substituting it breaks behaviour, the inheritance is a lie.

Asked atAmazonGoogleMicrosoft
step 1 / 9
1/2Square breaks the contract
Rectangle
- w, h: int
+ setWidth(w)
+ setHeight(h)
+ area()
Square
+ setWidth(w) ⚠
+ setHeight(h) ⚠
Square breaks the contract
1class Rectangle {
2 void setWidth(int w){ this.w = w; }
3 void setHeight(int h){ this.h = h; }
4 int area(){ return w * h; }
5}
6class Square extends Rectangle {
7 void setWidth(int w){ this.w = w; this.h = w; } // ⚠ also sets height
8}

A Rectangle lets width and height move independently — that's its contract.