论坛首页 入门技术论坛

<Java.JavaEE面试整理>(7) --Polymorphism之深入理解(二)

浏览 1561 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-04-02  

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.

 

 

  • composiion_over_inheritance.zip (1.2 KB)
  • 描述: a clever way of solving a common problem through the use of object composition rather then a standard, less flexible, inheritance based solution.
  • 下载次数: 8
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics