下面给出一个根据雇员类型利用多态性完成工资单计算的程序。定义一个类Employee
作为超类,Employee
的子类有Boss(每星期发给他固定工资,而不计工作时间)、PieceWorker
(按其生产的产品数发放工资)、HourlyWorker
(根据工作时间长短发放工资)。对所有雇员类型都使用earnings()
方法完成其工资单的计算,但每个人挣的工资按他所属的雇员类计算,所有雇员类都是从超类Employee
派出生的。所以在超类中声明earnings()
方法,该方法没有实质性工作,而是在每个子类都提供恰当的earnings()
方法的重写。为了计算雇员的工资,程序仅使用雇员对象的一个超类引导并调用earnings()方法。
// 参考文件名 Ch3.java
//Employee超类的定义
class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return name;
}
public double earnings() {
return 0.0;
}
}
//定义Boss类,为Employee的子类
class Boss extends Employee {
private Double weeklySalary;
public Boss(String name, double s) { // 定义Boss类的构造方法
super(name);
setWeeklySalary(s);
}
public void setWeeklySalary(Double weeklySalary) {
this.weeklySalary = weeklySalary;
}
public double earnings() { // 重写父类的 earnings()方法
return weeklySalary;
}
public String toString() {
return "Boss: " + super.toString();
}
}
//定义PieceWorker类,为Employee的子类
class PieceWorker extends Employee {
private Double salary;
private Integer piece;
public PieceWorker(String name, Integer p, Double s) {
super(name);
setSalary(s);
setPiece(p);
}
public void setPiece(Integer p) {
this.piece = p;
}
public void setSalary(Double s) {
this.salary = s;
}
public double earnings() {
return piece * salary;
}
public String toString() {
return "PieceWorker: " + super.toString();
}
}
//定义HourlyWorker类,为Employee的子类
class HourlyWorker extends Employee {
private Double salary;
private Integer hour;
public HourlyWorker(String name, Integer h, Double s) {
super(name);
setSalary(s);
setHour(h);
}
public void setHour(Integer h) {
this.hour = h;
}
public void setSalary(Double s) {
this.salary = s;
}
public double earnings() {
return this.hour * salary;
}
public String toString() {
return "HourlyWorker: " + super.toString();
}
}
public class Ch3 {
public static void main(String args[]) {
Employee ref; // 定义一个父类声明ref
ref = new Boss("魏无羡", 3000); // 父类引用指向子类对象
System.out.println(ref + ", weeklySalary:" + ref.earnings());
ref = new PieceWorker("王也", 3, 400.0);
System.out.println(ref + ", weeklySalary:" + ref.earnings());
ref = new HourlyWorker("张小凡", 13, 34.0);
System.out.println(ref + ", weeklySalary:" + ref.earnings());
}
}
仅供参考,欢迎指正、交流、学习,摇一摇