OO编程中的子类型化和继承之间有什么区别? [英] What is the difference between subtyping and inheritance in OO programming?

查看:78
本文介绍了OO编程中的子类型化和继承之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到主要区别.当我们可以使用继承和子类型化时,我感到非常困惑.我找到了一些定义,但定义不是很清楚.

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的对象上调用,则类型BA的子类型.
  • 继承是指实现的重用.如果B的某些功能是根据A的功能编写的,则类型B将从另一种类型A继承.
  • 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.

但是,子类型化和继承不必并驾齐驱.考虑数据结构双端队列(双端队列).双端队列支持两端的插入和删除,因此它具有四个功能insert-frontdelete-frontinsert-reardelete-rear.如果仅使用insert-reardelete-front,则会得到一个普通队列.另一方面,如果仅使用insert-frontdelete-front,则会得到一个堆栈.换句话说,我们可以根据双端队列来实现队列和堆栈,因此数据类型StackQueueDeque继承.另一方面,StackQueue都不是Deque的子类型,因为它们不支持Deque提供的所有功能.实际上,在这种情况下,DequeStackQueue的子类型!

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆