<Java.JavaEE面试整理>(7) --Polymorphism之深入理解(二)
关键字: composition or inheritanceQ. 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.
发表评论
提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则
- 浏览: 29382 次
- 性别:

- 来自: 北京

- 详细资料
搜索本博客
链接
最新评论
-
对浏览器中的context menu ...
Drag dropper
-- by whqida -
Spring中的load-time weav ...
没啥,有些class不在spring的管理之中,通过 load-time wea ...
-- by ray_linn -
对浏览器中的context menu ...
别搞笑了, 这是浏览器的 Context Menu? 这只不过是响应了鼠标右击事 ...
-- by fcoffee -
IE tab在Firefox里开发时 ...
firebug只能用于ff, 并不能用于ff下的ietab, 原因显而易见.如果 ...
-- by fcoffee -
IE tab在Firefox里开发时 ...
还网告知 该如何操作呢 我还是要到ie下再调试啊
-- by jianfeng008cn






评论排行榜