你真的了解多态吗?
来源于 跟着韩老师学java,https://www.bilibili.com/video/BV1fh411y7R8
一个案例彻底理解多态
定义员工类Employee
package com.zut.dynamic;
/**
* @author wzl
* @create 2021--09-06 21:27
*/
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
package com.zut.dynamic;
/**
* @author wzl
* @create 2021--09-06 21:29
*/
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();
}
}
定义经理类
package com.zut.dynamic;
/**
* @author wzl
* @create 2021--09-06 21:32
*/
public class manager extends Employee {
public manager(String name, double salary, double bonus) {
super(name, salary);
this.bonus = bonus;
}
private double bonus;
public void manage(){
System.out.println("经理"+getName()+"在工作");
}
@Override
public double getAnnual() {
return super.getAnnual() + bonus ;
}
}
编写测试类
package com.zut.dynamic;
/**
* @author wzl
* @create 2021--09-06 21:42
*/
public class ployParameter {
public static void main(String[] args) {
worker tom = new worker("tom",200);
manager john = new manager("liming",200,200000);
ployParameter ploy = new ployParameter();
ploy.showEmpAnnual(tom);
ploy.showEmpAnnual(john);
ploy.testWork(tom);
ploy.testWork(john);
}
//实现获取任何员工的年工资,并在main中调用该方法
public void showEmpAnnual(Employee employee){
System.out.println(employee.getName()+":"+employee.getAnnual()); //动态绑定机制
}
//添加一个方法,testWork,如果是普通员工,则调用 work 方法,如果是经理,则调用 manage 方法
public void testWork(Employee employee){
if(employee instanceof worker){
((worker) employee).work();//向下转型
}else if(employee instanceof manager){
((manager) employee).manage();//向下转型
}else {
System.out.println("不做处理");
}
}
}