java案例4-6经理与员工(利用多态实现)
时间: 2024-12-12 08:17:11 浏览: 5
java-learning-学习-java继承和多态之接口
在Java中,我们可以使用多态来实现“经理”和“员工”之间的关联,这是一个经典的继承和多态应用实例。我们首先创建一个基类`Employee`,然后定义两个子类`Manager`和`Salesman`,它们都继承自`Employee`。
```java
// 基类 Employee
public class Employee {
private String name;
private int id;
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
// 简单的公共方法
public void work() {
System.out.println(name + " is working.");
}
}
// 子类 Manager
public class Manager extends Employee {
public Manager(String name, int id) {
super(name, id);
}
@Override
public void work() {
System.out.println(name + " is managing a team.");
}
}
// 另一个子类 Salesman
public class Salesman extends Employee {
public Salesman(String name, int id) {
super(name, id);
}
@Override
public void work() {
System.out.println(name + " is making sales calls.");
}
}
```
在这个例子中,`Manager`和`Salesman`都有各自的`work()`方法实现了对父类`Employee`中`work()`方法的重写。当我们创建一个`Employee`类型的数组,并通过这个数组引用`Manager`或`Salesman`的对象时,就可以调用他们各自特有的`work()`方法:
```java
public static void main(String[] args) {
Employee[] employees = new Employee[2];
employees[0] = new Manager("Alice", 101);
employees[1] = new Salesman("Bob", 102);
for (Employee employee : employees) {
employee.work(); // 输出取决于实际对象类型
}
}
```
阅读全文