写代码前,先创建一个名为inheritance(继承)的包,以下所有代码都在该包中创建。
员工类
此类可直接复制。
package inheritance;
import java.time.LocalDate;
public class Employee {
private final String name; // 姓名
private double salary; // 薪水
private final LocalDate hireDay; // 入职日期
public Employee(String name, double salary, int year, int month, int day) {
this.name = name;
this.salary = salary;
hireDay = LocalDate.of(year, month, day);
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public LocalDate getHireDay() {
return hireDay;
}
public void raiseSalary(double byPercent) {
double raise = salary * byPercent / 100;
salary += raise;
}
}
经理类
package inheritance;
public class Manager extends Employee {
private double bonus; // 奖金
public Manager(String name, double salary, int year, int month, int day) {
super(name, salary, year, month, day);
}
public double getSalary() {
double baseSalary = super.getSalary(); // 获取基本工资
return baseSalary + bonus; // 薪水=基本工资+奖金
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
}
经理Test类
package inheritance;
public class ManagerTest {
public static void main(String[] args) {
// 创建一个Manager对象,固定工资为15000
Manager boss = new Manager("张三", 15000, 2019, 7, 1);
boss.setBonus(5000); // 设置额外5000奖金
boss.getSalary();
Employee[] staff = new Employee[3];
// 用Manager对象以及Employee对象填充员工数组,这里涉及"多态",可自行预学
staff[0] = boss;
staff[1] = new Employee("李四", 5000, 2022, 7, 15);
staff[2] = new Employee("王五", 6500, 2023, 7, 15);
// 输出所有员工对象的信息
for (Employee e : staff) {
System.out.printf("name=%s,salary=%.2f\n", e.getName(), e.getSalary());
}
}
}
输出:
name=张三,salary=20000.00
name=李四,salary=5000.00
name=王五,salary=6500.00