以员工类为超类如下:
//员工类(超类)
import java.time.LocalDate;
public class Employee {
//定义超类员工类(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;
}
}
以这个员工类为基础,写经理类,,经理工资在员工基本工资的基础上,额外加上奖金,如下:
// 经理类(子类)继承员工类(超类)
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;
}
}
最后我们进行测试,用员工和经理做比对:
//进行测试
public class ManagerTest {
public static void main(String[] args) {
//构造对象
Manager boss = new Manager("张三", 18000, 2000, 12, 15);
boss.setBonus(500);
Employee e = new Employee("李四", 5500, 2020, 10, 1);
System.out.printf("%s, %.2f\n", e.getName(), e.getSalary());
// => 李四, 5500.00
e = boss;
System.out.printf("%s, %.2f\n", e.getName(), e.getSalary());
// => 张三, 18500.00
}
}
总结:利用JAVA中的 ” 继承 “ 机制,让子类继承超类的内容,大大减少了重复代码,使代码更加简洁明了。