JAVA使用继承和多态解决公司支出的总薪水问题

abstract class Employee {
public abstract double earnings();
}
class YearWorker extends Employee {
//重写earnings()方法
}
class MonthWorker extends Employee {
//重写earnings()方法
}
class WeekWorker extends Employee {
//重写earnings()方法。
}
class Company {
Employee[] employee;
double salaries=0;
Company(Employee[] employee) {
this.employee=employee;
}
public double salariesPay() {
//计算salaries。
}

}
public class CompanySalary {
public static void main(String args[]) {
Employee [] employee=new Employee[29]; //公司有29名雇员
for(int i=0;i<employee.length;i++) { //雇员简单地分成三类
if(i%3==0)
employee[i]=new WeekWorker();
else if(i%3==1)
employee[i]=new MonthWorker();
else if(i%3==2)
employee[i]=new YearWorker();
}
Company company=new Company(employee);
System.out.println("公司薪水总额:"+company.salariesPay()+"元");
}
}
上述代码中要重写earnings方法,和计算salaries,怎么做呀,资料的讲解不会,要是增加多增加一种雇员该怎么改代码?

0

2个回答

 class YearWorker extends Employee {
//重写earnings()方法
@override
public double earnings() {
return 2000;
}
}
class MonthWorker extends Employee {
//重写earnings()方法
@override
public double earnings() {
return 3000;
}
}
class WeekWorker extends Employee {
//重写earnings()方法。 
@override
public double earnings() {
return 4000;
}
}
薪水我随便定的哦

增加一种雇员你按照现有的加上一个新的类
class XXXWorker extends Employee
重写 earnings()
用 employee[i]=new XXXWorker(); 创建

public double salariesPay() {
//计算salaries。
double sum = 0;
for (Employee e : employee)
{
sum += e.earnings();
}
return sum;
}
0

重写earings()方法:

 YearWorker:
 public double earings(){
 return 40000;
 }
 MothWorker;
 public double earings(){
 return 12*3000;
 }
 WeekWorker;
 public double earings(){
 return 12*4*700;
 }

如果增加一种雇员,需要在Emplyee类中再增加一类重写方法,假设是DayWorker,增加一类重写方法

 public double earnings(){
 return 365*100;
 }

同时在CompanySalary中,修改循环语句:

 for(int i=0;i<emploree.length;i++){
 if(i%4==0)
 employee[i]=new DayWorker();
  if(i%4==1)
 employee[i]=new WeekWorker();
  if(i%4==2)
 employee[i]=new MothWorker();
  if(i%4==3)
 employee[i]=new YearWorker();
0
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!