问题描述
我正在阅读有关面向对象编程语言的类的一些幻灯片,并逐步进入类型-子类型定义:
I'm reading some slides of a class on object oriented programming languages and stepped into the type-subtype definition:
Barbara Liskov,数据抽象和层次结构",SIGPLAN公告,23,5(1988年5月):
Barbara Liskov, "Data Abstraction and Hierarchy," SIGPLAN Notices,23,5 (May, 1988):
然后举一个例子:
我们可以说正点≤点吗?
Can we say that PositivePoint ≤ Point?
是的,因为类型为PositivePoint的元素可能总是 在以下程序中定义的程序中替换Point类型的元素 要点!
Yes, because an element of type PositivePoint may always replace an element of type Point in a program defined in Point terms!
现在...对我来说,似乎应该恰好相反:Point≤PositivePoint,因为我无法在使用带有负坐标的Point的程序中使用PositivePoint,而我可以相反.
Now... for me it seems it should be quite the opposite: Point ≤ PositivePoint because I couldn't use PositivePoint in a program that uses Point with negative coordinates, while I could to the opposite.
我怀疑语法是Type ≤ Sub-type
还是Sub-Type ≤ Type
,但是该语句看起来更清楚了,那又是怎么了?
I doubted if the syntax was Type ≤ Sub-type
or Sub-Type ≤ Type
, but the statement seems more clear, what's wrong then?
只是使事情变得简单,问题是:您可以说PositivePoint
是Point
的子类型吗?为什么?
Just to make things easier the question is:Can you say that PositivePoint
is a subtype of Point
?Why?
我在这里报告我在评论中写的内容,希望它可以使我的问题更清楚:
I report here what I wrote in a comment hoping it will make my problem clearer:
推荐答案
Liskov是正确的,PositivePoint≤Point,因为PositivePoint是Point的改进.任何使用Point的代码也必须能够使用PositivePoint,因为总有可能Point的坐标无论如何都是正的.反之则不成立,因为使用PositivePoint的代码可能会在假设坐标始终为正的情况下起作用,而用Point替换PositivePoint将破坏该假设.
Liskov is correct, PositivePoint ≤ Point, because PositivePoint is a refinement of Point. Any code that uses Point must also be able to use PositivePoint, because there was always the possibility that Point's coordinates were positive anyway. The reverse is not true, because code using PositivePoint may act under the assumption that the coordinates are always positive, and replacing PositivePoint with Point would break that assumption.
请注意,她并不是说PositivePoint可以代替Point,而只是在需要Point的地方可以使用PositivePoint.
Note that she's not saying that a PositivePoint can replace a Point, just that a PositivePoint can be used where a Point is needed.
这篇关于类型-子类型关系.似乎不清楚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!