OO编程中的子类型化和继承之间有什么区别? [英] What is the difference between subtyping and inheritance in OO programming?
问题描述
我找不到主要区别.当我们可以使用继承和子类型化时,我感到非常困惑.我找到了一些定义,但定义不是很清楚.
I could not find the main difference. And I am very confused when we could use inheritance and when we can use subtyping. I found some definitions but they are not very clear.
在面向对象编程中子类型化和继承之间有什么区别?
What is the difference between subtyping and inheritance in object-oriented programming?
推荐答案
In addition to the answers already given, here's a link to an article I think is relevant. Excerpts:
在面向对象的框架中,继承通常表示为一种功能,当人们在类的层次结构中组织抽象数据类型时,继承与子类型并存.但是,这两个是正交的想法.
In the object-oriented framework, inheritance is usually presented as a feature that goes hand in hand with subtyping when one organizes abstract datatypes in a hierarchy of classes. However, the two are orthogonal ideas.
- 子类型化是指接口的兼容性.如果可以在类型为
A
的对象上调用的每个函数也可以在类型为B
的对象上调用,则类型B
是A
的子类型. - 继承是指实现的重用.如果
B
的某些功能是根据A
的功能编写的,则类型B
将从另一种类型A
继承.
- Subtyping refers to compatibility of interfaces. A type
B
is a subtype ofA
if every function that can be invoked on an object of typeA
can also be invoked on an object of typeB
. - Inheritance refers to reuse of implementations. A type
B
inherits from another typeA
if some functions forB
are written in terms of functions ofA
.
但是,子类型化和继承不必并驾齐驱.考虑数据结构双端队列(双端队列).双端队列支持两端的插入和删除,因此它具有四个功能insert-front
,delete-front
,insert-rear
和delete-rear
.如果仅使用insert-rear
和delete-front
,则会得到一个普通队列.另一方面,如果仅使用insert-front
和delete-front
,则会得到一个堆栈.换句话说,我们可以根据双端队列来实现队列和堆栈,因此数据类型Stack
和Queue
从Deque
继承.另一方面,Stack
和Queue
都不是Deque
的子类型,因为它们不支持Deque
提供的所有功能.实际上,在这种情况下,Deque
是Stack
和Queue
的子类型!
However, subtyping and inheritance need not go hand in hand. Consider the data structure deque, a double-ended queue. A deque supports insertion and deletion at both ends, so it has four functions insert-front
, delete-front
, insert-rear
and delete-rear
. If we use just insert-rear
and delete-front
we get a normal queue. On the other hand, if we use just insert-front
and delete-front
, we get a stack. In other words, we can implement queues and stacks in terms of deques, so as datatypes, Stack
and Queue
inherit from Deque
. On the other hand, neither Stack
nor Queue
are subtypes of Deque
since they do not support all the functions provided by Deque
. In fact, in this case, Deque
is a subtype of both Stack
and Queue
!
正如我已经指出的那样,我认为Java,C ++,C#及其类似物将这两种思想整合到一个单一的类层次结构中,这导致了混乱.但是,我认为上面给出的示例在某种程度上与语言无关,确实使这些想法正确无误.我相信其他人可以举更多的例子.
I think that Java, C++, C# and their ilk have contributed to the confusion, as already noted, by the fact that they consolidate both ideas into a single class hierarchy. However, I think the example given above does justice to the ideas in a rather language-agnostic way. I'm sure others can give more examples.
这篇关于OO编程中的子类型化和继承之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!