基于多态的职工管理系统
时间: 2023-07-09 12:08:02 浏览: 186
C++职工管理系统:本教程主要利用C++来实现一个基于多态的职工管理系统
职工管理系统可以采用面向对象的方式进行设计和开发,其中多态可以用来实现不同职工类型之间的差异化处理。下面是一个简单的示例:
首先,定义一个抽象类 `Employee`,表示职工的基本属性和方法:
```java
public abstract class Employee {
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
public abstract void work();
}
```
然后,定义不同类型的职工类,继承自 `Employee`,并实现各自的特定方法。比如:
```java
public class Manager extends Employee {
private String department;
public Manager(String name, int age, double salary, String department) {
super(name, age, salary);
this.department = department;
}
public String getDepartment() {
return department;
}
@Override
public void work() {
System.out.println("I am managing the department " + department);
}
}
public class Engineer extends Employee {
private String project;
public Engineer(String name, int age, double salary, String project) {
super(name, age, salary);
this.project = project;
}
public String getProject() {
return project;
}
@Override
public void work() {
System.out.println("I am working on the project " + project);
}
}
```
最后,使用一个职工管理类 `EmployeeManager`,来对不同类型的职工进行管理。这里采用多态的方式,即使用父类 `Employee` 的引用来指向不同类型的子类对象,实现对不同类型职工的统一处理:
```java
public class EmployeeManager {
public static void main(String[] args) {
Employee manager = new Manager("Tom", 30, 10000, "HR");
Employee engineer = new Engineer("Jerry", 25, 8000, "AI");
manager.work();
engineer.work();
}
}
```
输出结果如下:
```
I am managing the department HR
I am working on the project AI
```
可以看到,通过多态的方式,我们可以实现对不同类型的职工进行统一处理,而不需要针对每种类型的职工编写不同的代码。
阅读全文