输出一组公司员工的信息列表,其中员工具备以下特征 雇员:员工编号、姓名、工资; 经理:员工编号、姓名、工资、管理部门; 总监:员工编号、姓名、工资、津贴;要求用java写一段代码,要求用到继承类和多态类,不要抽象类,用eclipse书写
时间: 2024-11-22 10:35:11 浏览: 6
在Java中,我们可以使用继承来创建一个多态模型来表示公司员工的不同职位层次,如普通员工、经理和总监。下面是一个简单的示例,展示了如何使用`Employee`基类以及两个派生类`Manager`和`Director`来实现这个需求:
```java
// 基类 Employee
class Employee {
private String id;
private String name;
private double salary;
public Employee(String id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
// 获取信息的方法
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Employee{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
// 继承类 Manager 和 Director
class Manager extends Employee {
private String department;
public Manager(String id, String name, double salary, String department) {
super(id, name, salary);
this.department = department;
}
public String getDepartment() {
return department;
}
@Override
public String toString() {
return "Manager{" +
"super." + super.toString() +
", department='" + department + '\'' +
'}';
}
}
class Director extends Employee {
private double bonus;
public Director(String id, String name, double salary, double bonus) {
super(id, name, salary);
this.bonus = bonus;
}
public double getBonus() {
return bonus;
}
@Override
public String toString() {
return "Director{" +
"super." + super.toString() +
", bonus=" + bonus +
'}';
}
}
public class Main {
public static void main(String[] args) {
// 创建实例并打印
Employee emp1 = new Employee("001", "张三", 5000);
System.out.println(emp1);
Manager manager1 = new Manager("002", "李四", 8000, "销售部");
System.out.println(manager1);
Director director1 = new Director("003", "王五", 12000, 2000);
System.out.println(director1);
}
}
```
在这个例子中,`Employee`是基础类,`Manager`和`Director`分别继承自它,并添加了部门和津贴属性。通过这种方式,我们实现了多态,因为`Manager`和`Director`都是`Employee`类型的实例,可以共享相同的`getId()`、`getName()`和`getSalary()`方法,但在实际操作中会显示各自特有的信息。
阅读全文