输出一组公司员工的信息列表,其中员工具备以下特征 雇员:员工编号、姓名、工资; 经理:员工编号、姓名、工资、管理部门; 总监:员工编号、姓名、工资、津贴;要求用java写一段代码,要求用到继承类和多态类,不要抽象类
时间: 2024-11-23 17:38:45 浏览: 11
在Java中,我们可以创建一个通用的`Employee`类作为基础类,并通过继承创建具体的`Manager`和`Director`类来体现多态。这里是一个简单的例子:
```java
// 基础员工类 Employee
public 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 void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getSalary() { return salary; }
public void setSalary(double salary) { this.salary = salary; }
@Override
public String toString() {
return "Employee{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
// 继承自Employee的经理 Manager
public 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; }
public void setDepartment(String department) { this.department = department; }
@Override
public String toString() {
return "Manager{" +
"department='" + department + '\'' +
"} " + super.toString();
}
}
// 继承自Employee的总监 Director
public 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; }
public void setBonus(double bonus) { this.bonus = bonus; }
@Override
public String toString() {
return "Director{" +
"bonus=" + bonus +
"} " + super.toString();
}
}
// 测试部分
public static void main(String[] args) {
Director director = new Director("001", "张三", 15000, 2000);
Manager manager = new Manager("002", "李四", 12000, "销售部");
System.out.println(director); // 输出 Director{...}
System.out.println(manager); // 输出 Manager{...}
}
```
在这个例子中,`Manager`和`Director`都继承了`Employee`类,实现了多态,因为它们都有相同的属性(如`id`, `name`, 和 `salary`),但每个类还有额外的特性(如`department` 对于经理,`bonus` 对于总监)。在`main`函数中,可以将它们视为`Employee`类型的实例并打印出来,体现了多态的优势。
阅读全文