package lab3;
abstract class Employee {
public abstract double earnings();
}
class YearWorker extends Employee {
@Override
public double earnings() {
return 100000;
}
}
class MonthWorker extends Employee {
@Override
public double earnings() {
return 10000*12;
}
}
class WeekWorker extends Employee {
@Override
public double earnings() {
return 5000*4*12;
}
}
class Company {
Employee[] employees;
double salaries = 0;
Company(Employee[] employees) {
this.employees = employees;
}
public double salariesPay() {
salaries = 0;
//计算salaries
for(int i =0; i < employees.length;i++) {
salaries += employees[i].earnings();
}
return salaries;
}
}
public class HardWork {
public static void main(String[] args) {
Employee[] employees = new Employee[20];
for (int i = 0; i < employees.length; i++) {
if(i%3==0)
employees[i] = new WeekWorker();
else if(i%3==1)
employees[i] = new MonthWorker();
else if(i%3==2)
employees[i] = new YearWorker();
}
Company company = new Company(employees);
System.out.println("公司年工资总额:" + company.salariesPay());
}
}
2. 掌握上转型对象的使用,多态的特性
最新推荐文章于 2024-11-15 18:38:47 发布
本文介绍了Java中使用抽象类和继承实现的Employee结构,展示了一个Company类如何根据员工类型(如周工、月工和年薪工)计算总薪资。在HardWork类的main方法中,创建了不同类型的员工并计算了公司年度工资总额。
摘要由CSDN通过智能技术生成