继承与构成的区别 [英] Difference between Inheritance and Composition

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

问题描述

组成和继承是否相同?
如果我想实现组合模式,我该如何用Java实现?

Are Composition and Inheritance the same? If I want to implement the composition pattern, how can I do that in Java?

推荐答案

它们完全不同。继承是is-a关系。作文是has-a

They are absolutely different. Inheritance is an "is-a" relationship. Composition is a "has-a".

你通过拥有另一个类的实例 C 作为您班级的一个字段,而不是扩展 C 。组合比继承更好的一个好例子是 java.util.Stack ,目前扩展 java.util.Vector 。现在这被认为是一个大错。堆栈is-NOT-a向量;不应该允许任意插入和删除元素。它应该是组合而已。

You do composition by having an instance of another class C as a field of your class, instead of extending C. A good example where composition would've been a lot better than inheritance is java.util.Stack, which currently extends java.util.Vector. This is now considered a blunder. A stack "is-NOT-a" vector; you should not be allowed to insert and remove elements arbitrarily. It should've been composition instead.

不幸的是,现在纠正这个设计错误为时已晚,因为现在更改继承层次结构会破坏与现有代码的兼容性。 如果 Stack 使用了合成而不是继承,可以随时修改它以使用其他数据结构而不违反API

Unfortunately it's too late to rectify this design mistake, since changing the inheritance hierarchy now would break compatibility with existing code. Had Stack used composition instead of inheritance, it can always be modified to use another data structure without violating the API.

我强烈推荐Josh Bloch的书 Effective Java 2nd Edition

I highly recommend Josh Bloch's book Effective Java 2nd Edition


  • 第16项:赞成组合优于继承

  • 第17项:继承的设计和文件,否则禁止它

良好的面向对象设计不是关于自由扩展现有类。你的第一直觉应该是改编。

Good object-oriented design is not about liberally extending existing classes. Your first instinct should be to compose instead.

参见:

  • Composition versus Inheritance: A Comparative Look at Two Fundamental Ways to Relate Classes

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

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