继承与组合 [英] Inheritance vs Composition

查看:105
本文介绍了继承与组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

首选组合而不是继承?

我想知道,为什么(或者当有太多的缺点时,应该考虑继承而不是组合:

I wonder, why (or in which cases) should one consider inheritance instead of composition when there are so much cons of it:


  • 如果我们在a中实现/覆盖方法调用超类方法的子类,不能保证我们的超类的另一个版本(可能是某些库)不会破坏我们的代码

  • 如果超类中会出现一个新方法与sublclass方法具有相同的签名,但具有不同的返回类型,我们的类将无法编译。

因此,我可以不要想象,地球上我们如何依赖它。超类作者可能希望提高性能,我们的客户代码可能会崩溃。

Therefore, I can't imagine, how on Earth we can rely on it. The superclass author may want to improve the performance and our client code may break down.

所以我的问题是:


  • 这些问题是如何解决的(例如在标准Java库中)?

  • 何时使用继承和组合?

推荐答案

您的第一个异议也适用于组合:如果您调用的方法的实现发生变化,那么不保证你的代码不会破坏。

Your first objection also applies to composition: if the implementation of a method that you call changes, there's no guarantee that your code won't break.

第二个异议实际上是一件好事,因为你会立即注意到新版本的问题API。

The second objection is actually a good thing, since you'll immediately notice there is a problem with the new version of the API.

问题与继承/组合没有太大关系。如果类的公共合同在不同版本之间发生变化,则必须对代码进行更改以适应这些更改。通过避免向后不兼容的更改来解决该问题。提供新的API可以是解决方案(例如,参见io,然后是nio,然后是nio2)。否则,发行说明和迁移文档可帮助从一个版本的API转换到另一个版本。

The problem doesn't have much to do with inheritance/composition. If the public contract of a class changes from version to version, you'll have to make changes in your code to accomodate these changes. The problem is solved by avoiding changes that would be backward-incompatible. Providing a new API can be the solution (See io, followed by nio, followed by nio2, for example). Otherwise, release notes and migration documentation are there to help transitioning from one version of an API to another.

当您的类之间存在is-a关系时,将使用继承和另一个班级。当您的类与另一个类之间存在has-a关系时,将使用组合。

Inheritance is used when there is a is-a relationship between your class and the other class. Composition is used when there is a has-a relationship between your class and the other class.

这篇关于继承与组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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