Q. Why would you prefer code reuse via composition over inheritance? Both the approaches make use of olymorphism and gives code reuse (in different ways) to achieve the same results but:
1,The advantage of class inheritance is that it is done statically at compile-time and is easy to use. The disadvantage of class inheritance is that because it is static, implementation inherited from a parent class cannot be changed at run-time. In object composition, functionality is acquired dynamically at run-time by objects collecting references to other objects. The advantage of this approach is that implementations can be replaced at run-time. This is possible because objects are accessed only through their interfaces, so one object can be replaced with another just as long as they have the same type. For example: the composed class AccountHelperImpl can be replaced by another more efficient implementation as shown below if required:
public class EfficientAccountHelperImpl implements AccountHelper {
public void deposit(double amount) {
System.out.println("efficient depositing " + amount);
}
public void withdraw(double amount) {
System.out.println("efficient withdrawing " + amount);
}
}
2,Another problem with class inheritance is that the subclass becomes dependent on the parent class
implementation. This makes it harder to reuse the subclass, especially if part of the inherited implementation is no longer desirable and hence can break encapsulation. Also a change to a superclass can not only ripple down the inheritance hierarchy to subclasses, but can also ripple out to code that uses just the subclasses making the design fragile by tightly coupling the subclasses with the super class. But it is easier to change the interface/implementation of the composed class.
Due to the flexibility and power of object composition, most design patterns emphasize object composition over
inheritance whenever it is possible. Many times, a design pattern shows a clever way of solving a common problem through the use of object composition rather then a standard, less flexible, inheritance based solution.
优选组合复用
本文探讨了为何在面向对象设计中倾向于使用组合而非继承来实现代码复用。通过组合,对象可以在运行时动态获取功能,并允许替换实现而不破坏封装。文章还讨论了继承的一些局限性,如静态绑定和紧密耦合问题。

被折叠的 条评论
为什么被折叠?



