6-4 设计Worker类及其子类
时间: 2024-05-11 07:14:12 浏览: 340
Java程序设计课程实验9-继承和抽象类
Worker类是一个抽象类,其中包含了姓名、工龄、工资三个属性,以及计算工资的抽象方法calculateSalary()。
其子类可以根据不同的职业特点进行设计,例如:
1. Programmer类:继承自Worker类,重写calculateSalary()方法,根据工龄计算薪资。
2. Salesman类:继承自Worker类,重写calculateSalary()方法,根据销售业绩计算薪资。
3. Manager类:继承自Worker类,重写calculateSalary()方法,根据固定薪资和奖金计算总薪资。
示例代码如下:
```
public abstract class Worker {
private String name;
private int yearsOfWorking;
private double salary;
public Worker(String name, int yearsOfWorking, double salary) {
this.name = name;
this.yearsOfWorking = yearsOfWorking;
this.salary = salary;
}
public String getName() {
return name;
}
public int getYearsOfWorking() {
return yearsOfWorking;
}
public double getSalary() {
return salary;
}
public abstract double calculateSalary();
}
public class Programmer extends Worker {
public Programmer(String name, int yearsOfWorking, double salary) {
super(name, yearsOfWorking, salary);
}
@Override
public double calculateSalary() {
return getSalary() * (1 + 0.1 * getYearsOfWorking());
}
}
public class Salesman extends Worker {
private double sales;
public Salesman(String name, int yearsOfWorking, double salary, double sales) {
super(name, yearsOfWorking, salary);
this.sales = sales;
}
public double getSales() {
return sales;
}
public void setSales(double sales) {
this.sales = sales;
}
@Override
public double calculateSalary() {
return getSalary() + 0.2 * getSales();
}
}
public class Manager extends Worker {
private double bonus;
public Manager(String name, int yearsOfWorking, double salary, double bonus) {
super(name, yearsOfWorking, salary);
this.bonus = bonus;
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
@Override
public double calculateSalary() {
return getSalary() + getBonus();
}
}
```
阅读全文