要求有一个接口,名为 Employee。该接口有一个抽象方法 earnings。实现 Employee 接口的 类有 YearPaidWorker、MonthPaidWorker、WeekPaidWorker。YearPaidWorker 按年领取薪水, MonthPaidWorker 按月领取薪水,WeekPaidWorker 按周领取薪水。要求所有重写接口中的 的 earnings 方法,实现薪水领取的具体方式。 编写 Company 类,该类有一个 Employee 对象数组,数组对象可以为 YearPaidWorker、 MonthPaidWorker、WeekPaidWorker。 要求实现输出 Company 对象一年需要支付的薪水总额。
时间: 2023-06-06 14:08:07 浏览: 93
接口和抽象类的区别(面向对象)
好的,这是一个关于 Java 接口和继承的问题。我可以回答这个问题,并且给出相应的代码示例。以下是实现代码:
```
// 定义 Employee 接口
public interface Employee {
public double earnings();
}
// YearPaidWorker 类实现 Employee 接口
public class YearPaidWorker implements Employee {
private double annualSalary;
public YearPaidWorker(double annualSalary) {
this.annualSalary = annualSalary;
}
@Override
public double earnings() {
return annualSalary;
}
}
// MonthPaidWorker 类实现 Employee 接口
public class MonthPaidWorker implements Employee {
private double monthlySalary;
public MonthPaidWorker(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
@Override
public double earnings() {
return monthlySalary * 12;
}
}
// WeekPaidWorker 类实现 Employee 接口
public class WeekPaidWorker implements Employee {
private double weeklySalary;
public WeekPaidWorker(double weeklySalary) {
this.weeklySalary = weeklySalary;
}
@Override
public double earnings() {
return weeklySalary * 52;
}
}
// Company 类
public class Company {
private Employee[] employees;
public Company(Employee[] employees) {
this.employees = employees;
}
public double totalEarnings() {
double total = 0;
for (Employee employee : employees) {
total += employee.earnings();
}
return total;
}
}
// 测试代码
public static void main(String[] args) {
Employee employee1 = new YearPaidWorker(120000);
Employee employee2 = new MonthPaidWorker(10000);
Employee employee3 = new WeekPaidWorker(2500);
Employee[] employees = { employee1, employee2, employee3 };
Company company = new Company(employees);
double totalEarnings = company.totalEarnings();
System.out.println("公司一年需要支付的薪水总额为:" + totalEarnings);
}
```
以上代码定义了 Employee 接口和三个实现接口的类: YearPaidWorker、 MonthPaidWorker、WeekPaidWorker。另外,Company 类维护了一个 Employee 对象数组,并提供了计算公司一年需要支付的薪水总额的方法。通过创建不同的 Employee 对象,并传入 Company 对象中进行计算,可以得到所需的结果。
阅读全文