定义员工类Employee,包含姓名和月工资[private],以及计算年工资getAnnual方法。普通员工和经理继承了员工,经理类多了奖金bonus属性和管理manage方去,普通员工类多了work方法,普通员工和经理类要求分别重写getAnnual方法则试类中添加一个方法showEmpAnnual(Employee e),实现获取任何员工对象的丰工资,并在main方法中调用该方法[e.getAnnual0]
试类中添加一个方法,testWork,如果是普通员工,则调用work方法,如果是经里,则调用manage方法
类Employee
package poly_polyparameter;
public class Employee {
private String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
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;
}
public double getAnnul() {
return 12 * this.salary;
}
}
普通员工类
package poly_polyparameter;
public class Worker extends Employee{
public Worker(String name, double salary) {
super(name, salary);
}
public void work() {
System.out.println("普通员工" + this.getName() + "正在工作");
}
@Override
public double getAnnul() {
return super.getAnnul();
}
}
经理类
package poly_polyparameter;
public class Manager extends Employee {
private double bonous;//奖金
public Manager(String name, double salary) {
super(name, salary);
}
public Manager(String name, double salary, double bonous) {
super(name, salary);
this.bonous = bonous;
}
@Override
public double getAnnul() {
return super.getAnnul() + this.bonous;
}
public void manage() {
System.out.println("经理" + this.getName() + "正在管理");
}
public double getBonous() {
return bonous;
}
public void setBonous(double bonous) {
this.bonous = bonous;
}
}
主函数
import poly_polyparameter.Employee;
import poly_polyparameter.Manager;
import poly_polyparameter.Worker;
public class Main {
public static void main(String[] args) {
Worker tom = new Worker("tom", 2500);
Manager milan = new Manager("milan", 5000, 200000);
Main main = new Main();
main.showEmpAnuul(tom);
main.showEmpAnuul(milan);
main.testWork(tom);
main.testWork(milan);
}
//实现获取任何员工对象的年工资,并在 main 方法中调用该方法 [e.getAnnual()]
public void showEmpAnuul(Employee e) {
System.out.println(e.getAnnul());//动态绑定机制
}
//添加一个方法,testWork,如果是普通员工,则调用 work 方法,如果是经理,则调用 manage 方法
public void testWork(Employee e) {
if (e instanceof Worker) {
((Worker) e).work();//向下转型
} else if (e instanceof Manager) {
((Manager) e).manage();
}else {
System.out.println("不能处理...");
}
}
}
编译结果

总结
多态参数总的来说还是要运行instanceof判断是否需要的类,是的话通过向下转型使用子类方法
本文定义了一个Employee类,包括姓名和月工资属性以及计算年工资的getAnnual方法。Worker和Manager类分别作为Employee的子类,添加了额外的方法。showEmpAnnual方法用于获取任何员工的年工资,testWork方法根据员工类型调用相应的工作或管理方法。通过instanceof关键字实现了多态参数的处理。

被折叠的 条评论
为什么被折叠?



