要求有一个abstract类,类名为Employee。Employee的子类有 YearWorker,MonthWorker, WeekWorker。YearWorker对象按年领取薪水,MonthWorker按月领取薪水,WeekWorker按周领取薪水。Employee类有一个abstract方法: public abstract earnings(); 子类必须重写父类的eanings()方法,给出各自领取薪水的具体方式。 按年领取薪水的计算方法是:12000 按月领取薪水的计算方法是:12*2300 按周领取薪水的计算方法是:52*780 另外有一个Company类,该类用Employee对象数组作为成员,Employee对象数组的单元可以是YearWorker对象的上转型对象、MonthWorker对象的上转型对象或WeekWorker对象的上转型对象。程序能输出Company对象一年需要支付的薪水总额。即Company需要一个带参的构造方法来初始化Employee数组,需要提供public double salariesPay()方法计算公司一年需要支付的薪水总额,并返回。
时间: 2024-02-11 13:04:42 浏览: 14
python继承和抽象类的实现方法
下面是实现上述要求的代码示例:
Employee.java:
```java
public abstract class Employee {
public abstract double earnings();
}
```
YearWorker.java:
```java
public class YearWorker extends Employee {
@Override
public double earnings() {
return 12000;
}
}
```
MonthWorker.java:
```java
public class MonthWorker extends Employee {
@Override
public double earnings() {
return 12 * 2300;
}
}
```
WeekWorker.java:
```java
public class WeekWorker extends Employee {
@Override
public double earnings() {
return 52 * 780;
}
}
```
Company.java:
```java
public class Company {
private Employee[] employees;
public Company(Employee[] employees) {
this.employees = employees;
}
public double salariesPay() {
double total = 0;
for (Employee employee : employees) {
total += employee.earnings();
}
return total;
}
}
```
MainClass.java:
```java
public class MainClass {
public static void main(String[] args) {
Employee[] employees = new Employee[3];
employees[0] = new YearWorker();
employees[1] = new MonthWorker();
employees[2] = new WeekWorker();
Company company = new Company(employees);
double totalSalaries = company.salariesPay();
System.out.println("Total salaries: " + totalSalaries);
}
}
```
运行上述代码,输出结果为:
```
Total salaries: 35760.0
```
其中,总薪水为12000 + 12 * 2300 + 52 * 780 = 35760.0。
阅读全文