继承与组合的区别 [英] Difference between Inheritance and Composition

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

问题描述

组合和继承是一样的吗?如果我想实现组合模式,我该如何在 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.

另见:

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

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