用java语言编写 1 某公司的人员分为员工和经理两种,但经理也属于员工中的一种,公司的人员都有自己的姓名、地址,工号、工资、工龄等属性,但经理不同于员工的是,经理有自己在公司对应的级别。另外,每次给员工涨工资一次只能涨10%,经理能涨20%。请利用多态实现给员工和经理涨工资。 提示信息: - 经理类(Managers)应该使员工(Employees)的子类 - Employees类中涨工资的方法changeSalary()可以被其子类Managers重写(多态)
时间: 2023-10-25 09:35:22 浏览: 50
以下是用 Java 语言实现的代码:
```java
class Employees {
private String name;
private String address;
private int emp_id;
private double salary;
private int years_of_service;
public Employees(String name, String address, int emp_id, double salary, int years_of_service) {
this.name = name;
this.address = address;
this.emp_id = emp_id;
this.salary = salary;
this.years_of_service = years_of_service;
}
public void changeSalary(double percentage) {
if (percentage <= 0) {
throw new IllegalArgumentException("The percentage must be positive.");
}
this.salary *= (1 + percentage / 100);
}
// Getters and setters
}
class Managers extends Employees {
private int level;
public Managers(String name, String address, int emp_id, double salary, int years_of_service, int level) {
super(name, address, emp_id, salary, years_of_service);
this.level = level;
}
@Override
public void changeSalary(double percentage) {
if (percentage <= 0) {
throw new IllegalArgumentException("The percentage must be positive.");
}
if (percentage > 20) {
throw new IllegalArgumentException("Managers can only get a maximum of 20% raise.");
}
this.salary *= (1 + percentage / 100);
}
// Getters and setters
}
public class Company {
public static void main(String[] args) {
Employees[] employees = {
new Employees("Alice", "123 Main Street", 1001, 50000, 3),
new Managers("Bob", "456 Oak Avenue", 1002, 80000, 5, 2),
new Employees("Charlie", "789 Pine Boulevard", 1003, 60000, 1)
};
for (Employees employee : employees) {
employee.changeSalary(10);
System.out.printf("%s: $%.2f\n", employee.getName(), employee.getSalary());
}
}
}
```
在代码中,Employees 类和 Managers 类都有一个构造函数和一个 changeSalary 方法,用于设置员工的基本信息和调整员工的薪水。Managers 类重写了父类的 changeSalary 方法,以实现不同的涨工资比例。
在主函数中,创建了一个包含三个员工的数组,然后对每个员工调用 changeSalary 方法,将薪水增加 10%(对于经理,最多只能增加 20%),最后输出每个员工的姓名和薪水。