gpt4 book ai didi

oop - OO 编程中的子类型化和继承有什么区别?

转载 作者:行者123 更新时间:2023-12-05 07:42:37 25 4
gpt4 key购买 nike

我找不到主要区别。我很困惑什么时候可以使用继承,什么时候可以使用子类型。我找到了一些定义,但它们不是很清楚。

在面向对象编程中,子类型化和继承有什么区别?

最佳答案

除了已经给出的答案,这里还有一个 link我认为相关的文章。摘录:

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.

  • Subtyping refers to compatibility of interfaces. A type B is a subtype of A if every function that can be invoked on an object of type A can also be invoked on an object of type B.
  • Inheritance refers to reuse of implementations. A type B inherits from another type A if some functions for B are written in terms of functions of A.

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# 和它们的同类产品造成了困惑,正如已经指出的那样,因为它们将这两种思想合并到一个类层次结构中。然而,我认为上面给出的例子以一种与语言无关的方式正确地表达了这些想法。我相信其他人可以举出更多例子。

关于oop - OO 编程中的子类型化和继承有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44331340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com