首先员工和经理一样,都是员工,但是员工自有自己的基础工资,经理可能还会有一些额外的奖金,所以用继承来实现一个简单的代码。
员工类:
package com.example.extend;
import java.time.LocalDate;
public class Employee {
private String name;
private double salary;
private 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;
}
/**
* 员工增加工资
* @param byPercent
*/
public void raiseSalary(double byPercent) {
double raise = salary*byPercent/100;
salary += raise;
}
}
经理类:
package com.example.extend;
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);
bonus = 0;
}
@Override
public double getSalary() {
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
}
测试类:
package com.example.extend;
public class ManagerTest {
public static void main(String[] args) {
// 构建一个管理员对象
Manager boss = new Manager("Renyuhua", 80000, 2018, 12, 30);
boss.setBonus(5000);
Employee[] staff = new Employee[2];
staff[0] = boss;
staff[1] = new Employee("zhangzhouzhou", 20000, 2000, 6, 14);
for (Employee employee : staff) {
employee.raiseSalary(5);
System.out.println("name = " + employee.getName() + ",salary = " + employee.getSalary());
}
}
}
最后的输出: