组合和继承是一样的吗? 如果我想实现组合模式,我如何在Java中做到这一点?
当前回答
@Michael Rodrigues给出的答案不正确(我道歉;我不能直接评论),这可能会导致一些混乱。
接口实现是一种继承形式…当你实现一个接口时,你不仅继承了所有的常量,你还将你的对象提交为接口指定的类型;这仍然是一种“是”的关系。如果汽车实现了Fillable,那么汽车“是-a”Fillable,并且可以在任何需要使用Fillable的代码中使用。
组合从根本上不同于继承。当您使用组合时,您(如其他回答所示)在两个对象之间建立了“has-a”关系,而不是使用继承时所建立的“is-a”关系。
所以,从其他问题中关于汽车的例子来看,如果我想说一辆汽车“有一个”油箱,我会使用如下的组合:
public class Car {
private GasTank myCarsGasTank;
}
希望这能消除任何误解。
其他回答
另一个例子,考虑一个汽车类,这将是一个很好的组合使用,一个汽车将“有”一个发动机,一个变速器,轮胎,座位,等等。它不会扩展任何这些类。
组合意味着有A 继承意味着IS A
例子:Car有引擎,Car是一辆汽车
在编程中,这被表示为:
class Engine {} // The Engine class.
class Automobile {} // Automobile class which is parent to Car class.
class Car extends Automobile { // Car is an Automobile, so Car class extends Automobile class.
private Engine engine; // Car has an Engine so, Car class has an instance of Engine class as its member.
}
在简单的词聚合意味着有一个关系..
复合是聚合的一种特殊情况。在更具体的方式中,受限聚合称为组合。当一个对象包含另一个对象时,如果被包含的对象没有容器对象的存在就不能存在,那么它被称为组合。 示例:一个类包含学生。学生离不开课堂。课堂和学生之间存在着互动。
为什么使用聚合
代码的可重用性
当使用聚合时
当没有is关系时,代码重用也最好通过聚合来实现
继承
继承是一种父子关系继承意味着是一种关系
java中的继承是一种机制,在这种机制中,一个对象获得父对象的所有属性和行为。
在Java中使用继承 1代码可重用性。 2在子类中添加额外的特性以及方法覆盖(这样可以实现运行时多态性)。
Though both Inheritance and Composition provides code reusablility, main difference between Composition and Inheritance in Java is that Composition allows reuse of code without extending it but for Inheritance you must extend the class for any reuse of code or functionality. Another difference which comes from this fact is that by using Composition you can reuse code for even final class which is not extensible but Inheritance cannot reuse code in such cases. Also by using Composition you can reuse code from many classes as they are declared as just a member variable, but with Inheritance you can reuse code form just one class because in Java you can only extend one class, because multiple Inheritance is not supported in Java. You can do this in C++ though because there one class can extend more than one class. BTW, You should always prefer Composition over Inheritance in Java, its not just me but even Joshua Bloch has suggested in his book
我认为这个例子清楚地解释了继承和组合之间的区别。
在本例中,使用继承和组合解决了这个问题。作者注意到;在继承中,父类的更改可能会导致继承它的派生类出现问题。
在这里,您还可以看到使用UML进行继承或组合时在表示上的区别。
http://www.javaworld.com/article/2076814/core-java/inheritance-versus-composition--which-one-should-you-choose-.html
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap