方法定义的形参为父类类型,实参为允许为子类类型
问题实践举例
定义员工类Employee,包含姓名和月工资[private],以及计算年工资getAnnual的方法。普通员工和经理继承了员工,经理类多了奖金bonus属性和管理manage方法,普通员工类多了work方法,普通员工和经理类要求分别重写getAnnual方法
测试类中添加一个方法,testWork,如果是普通员工,则调用work方法,如果是经
理,则调用manage方法
PloyParameter(用来执行)
package com.humouren.poly_.polyparameter;
public class PloyParameter {
public static void main(String[] args) {
Manager tom = new Manager("tom",2500);
Staff milan = new Staff("milan",30000,200000);
PloyParameter ployParameter = new PloyParameter();
ployParameter.showEmpAnnual(tom);
ployParameter.showEmpAnnual(milan);
ployParameter.testWork(tom);
ployParameter.testWork(milan);
}
public void showEmpAnnual(Employee e){
System.out.println(e.getAnnual());//有动态绑定机制
}
public void testWork(Employee e){
if(e instanceof Manager){
System.out.println(((Manager) e).work());
} else if (e instanceof Staff) {
System.out.println(((Staff) e).manage());
}else {
System.out.println("你的输入是错误的");
}
}
}
Employee(父类)
package com.humouren.poly_.polyparameter;
//员工父类,包括经理和普通员工
public class Employee {
private String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public double getAnnual(){
return salary*12;
}
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;
}
}
Manager(子类1)
package com.humouren.poly_.polyparameter;
//普通员工
public class Manager extends Employee{
public Manager(String name, double salary) {
super(name, salary);
}
@Override
public double getAnnual() {
return super.getAnnual();
}
public String work(){
return "员工"+getName()+"正在工作";
}
}
Staff(子类2,经理)
package com.humouren.poly_.polyparameter;
//经理
public class Staff extends Employee{
private double bonus;
public Staff(String name, double salary,double bonus) {
super(name, salary);
this.bonus = bonus;
}
public String manage(){
return "经理"+getName()+"正在管理";
}
public double getBonus() {
return bonus;
}
@Override
public double getAnnual() {
return super.getAnnual() + bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
}