(1)如果子类YearWorker不重写earnings()方法,程序编译将提示怎样的错误? (2)再增加一种雇员,并计算公司一年的总薪水。(编写代码)
时间: 2024-01-09 17:03:31 浏览: 142
计算工资的程序和代码
(1) 如果子类YearWorker不重写earnings()方法,程序编译将提示以下错误信息:
```
YearWorker is not abstract and does not override abstract method earnings() in Employee
```
这是因为Employee类中earnings()方法是抽象的,需要在子类中重写实现。如果子类没有重写,就无法创建YearWorker的实例,因为它是一个抽象类。
(2) 增加一种雇员,可以再创建一个子类,例如:
```java
class DayWorker extends Employee {
private double salary;
public DayWorker(double salary) {
this.salary = salary;
}
@Override
public double earnings() {
return salary * 365;
}
}
```
这个类代表按天领取薪水的雇员。earnings()方法返回薪水乘以365,表示一年的总薪水。
接下来在Main类中增加DayWorker的实例,并计算公司一年的总薪水:
```java
public static void main(String[] args) {
Employee[] employees = new Employee[4];
employees[0] = new YearWorker(50000);
employees[1] = new MonthWorker(4000);
employees[2] = new WeekWorker(800);
employees[3] = new DayWorker(200);
Company company = new Company(employees);
System.out.println("The company needs to pay " + company.totalPay() + " per year.");
}
```
这里增加了一个DayWorker的实例,薪水为每天200元。计算公司一年的总薪水时,会把这个员工的薪水乘以365加入总额中。
阅读全文