学以致用——Java源码——使用接口及多态处理应付账款(发票及员工工资)(更简单的方法)(Accounts Payable System Modification 2)

在上一习题中,通过修改Employee的各个子类,实现了使用接口及多态处理应付账款。

参考:

学以致用——Java源码——使用接口及多态处理应付账款(发票及员工工资)(Accounts Payable System Modification),

https://blog.csdn.net/hpdlzu80100/article/details/86001126

而紧接着的这道题则告诉我们这么一个道理:很多事情,有更为优雅的解决方法!

题目描述:

10.16 (Accounts Payable System Modification) It’s possible to include the functionality of the payroll application (Figs. 10.4–10.9) in the accounts payable application without modifying Employee subclasses SalariedEmployee, HourlyEmployee, CommissionEmployee or BasePlusCommission- Employee. To do so, you can modify class Employee (Fig. 10.4) to implement interface Payable and declare method getPaymentAmount to invoke method earnings. Method getPaymentAmount would then be inherited by the subclasses in the Employee hierarchy. When getPaymentAmount is called for a particular subclass object, it polymorphically invokes the appropriate earnings method for that subclass. Reimplement Exercise 10.15 using the original Employee hierarchy from the payroll application of Figs. 10.4–10.9. Modify class Employee as described in this exercise, and do not modify any of class Employee’s subclasses.

更简单的解法,即在Employee类中,添加一个新方法:

   @Override
   public double getPaymentAmount()
   {
      return earnings();
   }

其他的子类保持不变。

完整代码就不赘述了。

你可能感兴趣的:(Java编程(Java,Programming))