java中的composition和inheritance的区别

来源:百度知道 编辑:UC知道 时间:2024/06/20 07:51:42
在看THINKING IN JAVA时候。书中讲了composition和inheritance。这两个的区别在哪里没有看的很明白。哪位大侠指点下,最好举个例子。谢谢哦。

他们两者的能力几乎是一样的。主要区别就是在 你所需表达的概念上 。如果你需要的只是现有类的某种能力,而不是该类的接口,也就是说你只是需要现有类来做某种事情,而你创建的类与该类并没有类似的接口的话,你就应该使用 composition 。而 inheritance 的应用正好相反。也就是说你需要的是现有类的接口,也就是你希望在可以使用现有类的地方,也可以使用你新创建的类,那么这是你就应该是用 inheritance. Inheritance 的另外一个好处就是子类可以 upcast 到基类。 upcast 的作用就是在所有使用父类的地方你都可以使用子类(除非你使用的是 private 继承) 。这是因为子类继承了父类中的所有成员(除了一些特殊情况)。所以另外一个决定是使用 composition 或 inheritance 的方式就是问一下问题:你是否需要从新建的类 upcast 。

建议楼主看下Effective Java中的某条目,条目名是组合优先于继承.讲得很清楚明白...

都是复用的技术,但是各有优势..

Composition vs. Inheritance
Object composition and inheritance are two techniques for reusing functionality in object-oriented systems [7]. Class inheritance, or subclassing, allows a subclass' implementation to be defined in terms of the parent class' implementation. This type of reuse is often called white-box reuse. This term refers to the fact that with inheritance, the parent class implementation is often visible to the subclasses.

Object composition is a different method of r