多态参数(案列)
Employee parent class
package com.hspedu.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 12 * 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;
}
}
Worker subclass
package com.hspedu.poly_.polyparameter;
public class Worker extends Employee{
public Worker(String name, double salary) {
super(name, salary);
}
public void work(){
System.out.println("普通员工 " + getName() +" 正在工作....");
}
@Override
public double getAnnual() {//无额外收入,则直接调用
return super.getAnnual();
}
}
Manager subclass
package com.hspedu.poly_.polyparameter;
public class Manager extends Employee{
private double bonus;
public Manager(String name, double salary, double bonus) {
super(name, salary);
this.bonus = bonus;
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
//管理的方法
public void manage(){
System.out.println("经理 " + getName() + " 正在管理....");
}
//重写获取年薪的方法
@Override
public double getAnnual() {//额外加上奖金
return super.getAnnual() + bonus;
}
}
Polyparameter main class
package com.hspedu.poly_.polyparameter;
public class Polyparameter {
public static void main(String[] args) {
Worker tom = new Worker("tom", 2500);
Manager milan = new Manager("milan", 5000, 200000);
Polyparameter polyparameter = new Polyparameter();
polyparameter.showEmpAnnual(tom);
polyparameter.showEmpAnnual(milan);
polyparameter.testWork(tom);
polyparameter.testWork(milan);
}
//showEmpAnnual(Employee e)
public void showEmpAnnual(Employee e){
System.out.println(e.getAnnual());
}
//添加一个方法,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("不做处理....");
}
}
}
operation result