6. 继承练习 需求:实现某公司各种岗位(经理、销售人员、普通员工)的员工薪水计算,输出不同岗位各一名员工的工资。 要求: 1) 定义员工类,具有计算薪水的方法 2) 定义子类:经理类、销售人员类、普通员工类,分别继承员工类,重写计算薪水的方法 3) 定义测试类,包含输出薪水的方法,参数为员工对象(父类的引用指向子类的对象)java代码
时间: 2024-04-10 16:26:58 浏览: 129
```java
// 定义员工类
class Employee {
private String name;
private double baseSalary;
public Employee(String name, double baseSalary) {
this.name = name;
this.baseSalary = baseSalary;
}
public String getName() {
return name;
}
public double getBaseSalary() {
return baseSalary;
}
public double calculateSalary() {
return baseSalary;
}
}
// 定义经理类,继承员工类
class Manager extends Employee {
private double bonus;
public Manager(String name, double baseSalary, double bonus) {
super(name, baseSalary);
this.bonus = bonus;
}
@Override
public double calculateSalary() {
return getBaseSalary() + bonus;
}
}
// 定义销售人员类,继承员工类
class SalesPerson extends Employee {
private double commission;
public SalesPerson(String name, double baseSalary, double commission) {
super(name, baseSalary);
this.commission = commission;
}
@Override
public double calculateSalary() {
return getBaseSalary() + commission;
}
}
// 定义普通员工类,继承员工类
class OrdinaryEmployee extends Employee {
public OrdinaryEmployee(String name, double baseSalary) {
super(name, baseSalary);
}
}
// 定义测试类
class Test {
public static void printSalary(Employee employee) {
System.out.println("员工姓名:" + employee.getName());
System.out.println("员工薪水:" + employee.calculateSalary());
}
public static void main(String[] args) {
// 创建不同岗位的员工对象
Manager manager = new Manager("经理A", 5000, 2000);
SalesPerson salesPerson = new SalesPerson("销售人员B", 3000, 1000);
OrdinaryEmployee ordinaryEmployee = new OrdinaryEmployee("普通员工C", 2000);
// 输出员工薪水
printSalary(manager);
printSalary(salesPerson);
printSalary(ordinaryEmployee);
}
}
```
运行结果:
```
员工姓名:经理A
员工薪水:7000.0
员工姓名:销售人员B
员工薪水:4000.0
员工姓名:普通员工C
员工薪水:2000.0
```
以上是一个简单的实现,根据不同岗位的员工类进行薪水计算,并通过测试类进行输出。
阅读全文