某公司的人员分为员工和经理两种,但经理也属于员工中的一种,公司的人员都有自己的姓名和地址,员工和经理都有自己的工号、工资、工龄等属性。但经理与员工的不同之处在于,经理有自己在公司对应的级别 ,假设每次给员工涨一次工资能涨 10%,经理能涨 20%。本案例要求利用多态实现给员工和经理涨工资。用Java语言写出来
时间: 2023-10-25 22:27:42 浏览: 90
好的,以下是对应的Java代码:
```
public abstract class Employee {
private String name;
private String address;
private int employeeID;
private double salary;
private int yearsOfService;
public Employee(String name, String address, int employeeID, double salary, int yearsOfService) {
this.name = name;
this.address = address;
this.employeeID = employeeID;
this.salary = salary;
this.yearsOfService = yearsOfService;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public int getEmployeeID() {
return employeeID;
}
public double getSalary() {
return salary;
}
public int getYearsOfService() {
return yearsOfService;
}
public void setSalary(double newSalary) {
salary = newSalary;
}
public void raiseSalary(double percentage) {
salary += salary * percentage;
}
public abstract void work();
}
public class Manager extends Employee {
private int level;
public Manager(String name, String address, int employeeID, double salary, int yearsOfService, int level) {
super(name, address, employeeID, salary, yearsOfService);
this.level = level;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
@Override
public void work() {
System.out.println("As a manager, I manage the team");
}
@Override
public void raiseSalary(double percentage) {
super.raiseSalary(percentage * 2);
}
}
public class Main {
public static void main(String[] args) {
Employee emp1 = new Employee("John", "123 Main St", 1, 50000, 5);
Manager emp2 = new Manager("Jane", "456 Maple Ave", 2, 80000, 10, 2);
emp1.raiseSalary(0.1);
emp2.raiseSalary(0.1);
System.out.println(emp1.getName() + "'s new salary: " + emp1.getSalary());
System.out.println(emp2.getName() + "'s new salary: " + emp2.getSalary());
}
}
```
上面的代码中,我们定义了一个抽象的`Employee`类,其中包含了员工和经理通用的属性和方法,例如姓名、地址、工号、工资、工龄等,同时还有`raiseSalary`方法用来涨工资,这里我们使用了多态来实现不同类型的员工涨工资的不同方式。
然后我们再定义了一个`Manager`类,它继承自`Employee`类,除了拥有`Employee`类中的所有属性和方法外,还有自己的级别属性,并重写了`raiseSalary`方法,以实现经理和员工涨工资的不同方式。
最后在`Main`类中,我们创建了一个普通员工对象和一个经理对象,分别调用它们的`raiseSalary`方法来给它们涨工资,并输出结果。
阅读全文