【发布时间】:2015-01-20 17:19:28
【问题描述】:
我有一个超类 (Employee),它实现了一个只包含 1 个方法的接口,如下所示。
public interface Payable
{
double getPaymentAmount(); // calculate payment; no implementation
}
我有许多继承自 Employee 的子类(例如 SalariedEmployee、HourlyEmployee、CommissionEmployee),每个子类都包含一个方法 Earnings。
我被要求“可以修改 Employee 类以实现接口 Payable 并声明方法 getPaymentAmount 以调用方法 Earnings。然后方法 getPaymentAmount 将由 Employee 层次结构中的子类继承。当为特定子类对象调用 getPaymentAmount 时,它多态地为该子类调用适当的收益方法”。
如何在Employee类方法getPaymentAmount中调用相关的收入方法而不用编辑子类?
我是 Java 的新手。
Employee类的相关部分如下:
public abstract class Employee implements Payable
{
private String firstName;
private String lastName;
private String socialSecurityNumber;
// three-argument constructor
public Employee( String first, String last, String ssn )
{
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
} // end three-argument Employee constructor
//getters, settters, toString override etc have been deleted.
public double getPaymentAmount()
{
???? //This is what I need help with.
}
} // end abstract class Employee
并以子类为例:
public class SalariedEmployee extends Employee
{
private double weeklySalary;
// four-argument constructor
public SalariedEmployee(String first, String last, String ssn, double salary)
{
super(first, last, ssn); // pass to Employee constructor
setWeeklySalary(salary); // validate and store salary
} // end four-argument SalariedEmployee constructor
@Override
public double earnings()
{
return getWeeklySalary();
} // end method earnings
} // end class SalariedEmployee
【问题讨论】:
-
帮您什么,具体?
标签: java inheritance subclass