要求有一个abstract类,类名为Employee。Employee的子类有YearWorker、MonthWorker、WeekWorker。YearWorker对象按年领取薪水,MonthWorker对象按年领取薪水,WeekWorker对象按年领取薪水。Employee有一个abstract方法。 子类必须重写父类的earnings(),给出各自领取薪水的具体方式。另外有一个Company类,该类用Employee对象数据成员,Employee对象数组的单元可以是YearWorker对象的上转型对象或MonthWorker对象的上转型对象或WeekWorker对象的上转型对象。程序能输出Company对象一年需要支付的薪水总额。
时间: 2024-02-29 12:52:21 浏览: 127
好的,以下是一个实现上述需求的Java代码:
```java
abstract class Employee {
public abstract double earnings();
}
class YearWorker extends Employee {
private double salary;
public YearWorker(double salary) {
this.salary = salary;
}
@Override
public double earnings() {
return salary;
}
}
class MonthWorker extends Employee {
private double salary;
public MonthWorker(double salary) {
this.salary = salary;
}
@Override
public double earnings() {
return salary * 12;
}
}
class WeekWorker extends Employee {
private double salary;
public WeekWorker(double salary) {
this.salary = salary;
}
@Override
public double earnings() {
return salary * 52;
}
}
class Company {
private Employee[] employees;
public Company(Employee[] employees) {
this.employees = employees;
}
public double totalPay() {
double total = 0;
for (Employee e : employees) {
total += e.earnings();
}
return total;
}
}
public class Main {
public static void main(String[] args) {
Employee[] employees = new Employee[3];
employees[0] = new YearWorker(50000);
employees[1] = new MonthWorker(4000);
employees[2] = new WeekWorker(800);
Company company = new Company(employees);
System.out.println("The company needs to pay " + company.totalPay() + " per year.");
}
}
```
在这个程序中,Employee类是抽象类,定义了一个抽象方法earnings()。YearWorker、MonthWorker和WeekWorker类是Employee的子类,分别实现了earnings()方法来计算各自领取薪水的方式。
最后,Company类用Employee对象数据成员,Employee对象数组的单元可以是YearWorker对象的上转型对象或MonthWorker对象的上转型对象或WeekWorker对象的上转型对象。程序能输出Company对象一年需要支付的薪水总额。
阅读全文