所谓的多态参数就是:方法的形参类型是父类,实参类型是子类(用父类的引用接收子类的对象)
测试类:
package PolyParameter;
//方法的形参类型是父类,实参类型是子类
public class PolyParameter01 {
public static void main(String[] args) {
PolyParameter01 p01 = new PolyParameter01();
Empolyee empolyee = new Empolyee("员工一号",6000.45);
p01.showEmpAnnual(empolyee);
p01.testWork(empolyee);
putong putong1 = new putong("普通员工一号",5000.01);
p01.showEmpAnnual(putong1);
p01.testWork(putong1);
Manager m1 = new Manager("经理一号",10000.02,50000);
p01.showEmpAnnual(m1);
p01.testWork(m1);
}
//实现获取任何员工对象的年工资,并在 main 方法中调用该方法 [e.getAnnual()]
public void showEmpAnnual(Empolyee e){
System.out.println(e.getName()+" 的工资为 "+ e.GetAnnual());//动态绑定机制
}
//添加一个方法,testWork,如果是普通员工,则调用 work 方法,如果是经理,则调用 manage 方法
public void testWork(Empolyee e){//形参用父类来接收,这样就可以把子类对象传给父类引用
if (e instanceof Manager){
((Manager)e).manage();//向下转型
//简便写法 e. 直接弹出
}else if (e instanceof putong){
((putong)e).work();//向下转型(父类的引用强转成子类类型,然后调用子类的方法)
}else{
//nothing
}
}
}
父类:
package PolyParameter;
public class Empolyee {
private String name;
private double salary;
public Empolyee(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 GetAnnual(){
return 12*salary;
}
}
普通员工子类:
package PolyParameter;
public class putong extends Empolyee{
public putong(String name, double salary) {
super(name, salary);
}
//普通员工的特有方法
public void work(){
System.out.println("员工在工作");
}
//员工的年薪,重写方法
public double GetAnnual(){
return super.GetAnnual();
}
}
经理子类:
package PolyParameter;
public class Manager extends Empolyee{
private double bonus;
public Manager(String name, double salary, double bonus) {
super(name, salary);
this.bonus = bonus;
}
//经理的特有方法
public void manage(){
System.out.println("经理管理员工");
}
//重写年薪方法
public double GetAnnual(){
return super.GetAnnual() + bonus;
}
}