为什么 "Circle-ellipse" 的这个解决方案违反了 "Liskov Substition Principle"?

Why does this solution to the "Circle-ellipse" violate the "Liskov Substition Principle"?

Circle-Ellipse Problem.

中有一个违反里氏替换原则的好例子

a popular SO answer 中的措辞(尽管是矩形和正方形)如下:

In mathematics, a Square is a Rectangle. Indeed it is a specialization of a rectangle. The "is a" makes you want to model this with inheritance. However if in code you made Square derive from Rectangle, then a Square should be usable anywhere you expect a Rectangle. This makes for some strange behavior.

Imagine you had SetWidth and SetHeight methods on your Rectangle base class; this seems perfectly logical. However if your Rectangle reference pointed to a Square, then SetWidth and SetHeight doesn't make sense because setting one would change the other to match it. In this case Square fails the Liskov Substitution Test with Rectangle and the abstraction of having Square inherit from Rectangle is a bad one.

我的问题是 - 给定一个解决方案,我们在 Square 中覆盖 setWidth 并设置 widthheight同样的值,为什么还是违反了LSP?

确实违反了它,因为您承诺 setWidth() 会设置宽度而 setHeight() 会设置高度。 Square 会破坏 Rectangle 做出的这个(隐含的)承诺。