There's a nice example of violating the Liskov Substitution Principle in the Circle-Ellipse Problem.
Here is how it is phrased (albeit in terms of Rectangle and Square) in a popular SO answer:
In mathematics, a
Square
is aRectangle
. Indeed it is a specialization of a rectangle. The "is a" makes you want to model this with inheritance. However if in code you madeSquare
derive fromRectangle
, then aSquare
should be usable anywhere you expect aRectangle
. This makes for some strange behavior.Imagine you had
SetWidth
andSetHeight
methods on your Rectangle base class; this seems perfectly logical. However if your Rectangle reference pointed to aSquare
, thenSetWidth
andSetHeight
doesn't make sense because setting one would change the other to match it. In this case Square fails the Liskov Substitution Test withRectangle
and the abstraction of having Square inherit from Rectangle is a bad one.
My question is - Given a solution where we override setWidth
in Square
with an implementation that sets both width
and height
to the same value, why does it still violate LSP?