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

标签 oop liskov-substitution-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.

我的问题是 - 给定一个解决方案,我们使用设置 width 的实现来覆盖 Square 中的 setWidth > 和 height 为相同的值,为什么仍然违反 LSP?

最佳答案

它确实违反了它,因为您 promise setWidth() 将设置宽度,而 setHeight() 将设置高度。 Square 将打破 Rectangle 做出的这一(隐式) promise 。

关于oop - 为什么 "Circle-ellipse"的这个解决方案违反了 "Liskov Substition Principle"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49220013/

相关文章:

oop - 如何考虑子类型化的多态性

java - 集合子类型 - Liskov 替换原则

php - 抽象类-子类型

java - 有人不同意 : "using switch is bad OOP style"? 的说法吗

oop - 框架如何影响应用程序的架构?

java - 为什么我们不能直接访问对象而需要引用来完成我们的工作?

scala - `PartialFunction extends Function` 是否违反了 LSP?

c# - 继承自一个类,这是做什么的?

constructor - builder 应该遵守里氏替换原则吗?

java - 不同数据类型的里氏替换原理