练习4:用Java实现某公司的人员分为员工和经理两种,但经理也属于员工中的一种,公司的人员都有自己的姓名和地址,员工和经理都有自己的工号、工资、工龄等属性,但经理不同于员工的是,经理有自己在公司对应的级别。假设每次给员工涨工资一次能涨10,经理能涨20%。本案例要求利用多态实现给员工和经理涨工资。
时间: 2023-10-25 10:31:49 浏览: 253
以员工为编写一个程序,定义如下类:以员工为父类,该类包含员工的基本信息:姓名、年龄、部门。创建两个子类:经理类和工人类,输出经理和工人的工资。在父类中编写getSalary()方法,在子类中覆盖,实现多态。
5星 · 资源好评率100%
以下是实现该要求的Java代码:
```
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 void increaseSalary() {
salary += 10;
}
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;
}
}
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 void increaseSalary() {
salary *= 1.2;
}
public int getLevel() {
return level;
}
}
public class Company {
public static void main(String[] args) {
Employee employee1 = new Employee("John", "123 Main St.", 1001, 50000, 5);
Manager manager1 = new Manager("Jane", "456 Oak St.", 1002, 80000, 10, 2);
System.out.println("Before salary increase:");
System.out.println(employee1.getName() + " earns " + employee1.getSalary() + " per year.");
System.out.println(manager1.getName() + " earns " + manager1.getSalary() + " per year, and is at level " + manager1.getLevel() + " in the company.");
employee1.increaseSalary();
manager1.increaseSalary();
System.out.println("After salary increase:");
System.out.println(employee1.getName() + " earns " + employee1.getSalary() + " per year.");
System.out.println(manager1.getName() + " earns " + manager1.getSalary() + " per year, and is at level " + manager1.getLevel() + " in the company.");
}
}
```
在这段代码中,`Employee`类表示员工,`Manager`类表示经理,都继承自`Employee`类。`Employee`类有五个属性:姓名、地址、工号、工资和工龄,以及一个`increaseSalary()`方法,表示给员工涨工资。`Manager`类有一个额外的属性`level`,表示经理在公司中的级别,以及自己的`increaseSalary()`方法,表示给经理涨工资。
在主函数中,我们创建了一个`Employee`对象和一个`Manager`对象,然后分别调用它们的`increaseSalary()`方法来给它们涨工资。`Employee`对象的工资会增加10,而`Manager`对象的工资会增加20%。最后,我们输出员工和经理的新工资和经理的级别。
阅读全文