6-3 设计Worker类及其子类
时间: 2024-11-18 18:17:08 浏览: 21
④创建持久化类Personjava-Hibernate继承映射
6-3 设计`Worker`类及其子类是一个典型的设计模式,通常用于表示职业领域中有共同特性的工作者,同时允许特定类型的工作员有其额外的功能或属性。我们可以按照下面的步骤来设计:
首先,创建一个基础的`Worker`类,它包含一些通用的属性和方法:
```java
public class Worker {
private String name;
private int id;
protected double hourlyWage;
// 构造函数
public Worker(String name, int id, double hourlyWage) {
this.name = name;
this.id = id;
this.hourlyWage = hourlyWage;
}
// 获取和设置方法
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public double getHourlyWage() { return hourlyWage; }
// 公共方法,如工作小时数计算等
public double calculatePay(int hoursWorked) {
return hoursWorked * hourlyWage;
}
}
```
接着,我们可以为`Worker`类创建几个具体的子类,例如`OfficeWorker`, `BlueCollarWorker`等,它们继承自`Worker`并添加特有的属性和方法:
```java
// 办公室职员
public class OfficeWorker extends Worker {
private boolean hasLaptop;
public OfficeWorker(String name, int id, double hourlyWage, boolean hasLaptop) {
super(name, id, hourlyWage);
this.hasLaptop = hasLaptop;
}
// 特有的方法,如处理电子邮件等
public void sendEmail() {
System.out.println(name + " is sending an email.");
}
}
// 蓝领工人
public class BlueCollarWorker extends Worker {
private boolean usesSafetyEquipment;
public BlueCollarWorker(String name, int id, double hourlyWage, boolean usesSafetyEquipment) {
super(name, id, hourlyWage);
this.usesSafetyEquipment = usesSafetyEquipment;
}
// 特有的方法,如检查安全设备等
public void checkEquipment() {
System.out.println(name + " is checking safety equipment.");
}
}
```
阅读全文