package com.hspedu.poly_.polyaraneter_; public class Test { public static void main(String[] args) { Worker laLa = new Worker("laLa", 1000); Manager koko = new Manager("koko",1000,7000); Test test = new Test(); test.showEmployee(laLa); test.showEmployee(koko); test.testWork(laLa); test.testWork(koko); } public void showEmployee(Employee e) { System.out.println(e.getAnnual()); //动态绑定机制 } public void testWork(Employee e) { if (e instanceof Worker) { ((Worker) e).work(); //向下转型 } else if (e instanceof Manager) { ((Manager) e).manger(); //向下转型 } else { System.out.println("错了,宝儿"); } } }
package com.hspedu.poly_.polyaraneter_; //员工类 public class Employee { //共有的属性 private String name; private double salary; //构造器 public Employee(String name, double salary) { this.name = name; this.salary = salary; } //get set 方法 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 com.hspedu.poly_.polyaraneter_; //普通员工类 public class Worker extends Employee{ //构造器 public Worker(String name, double salary) { super(name, salary); } //普通员工类独有的方法 work public void work() { System.out.println(" 普通员工 " + getName() + " 正在摸鱼 "); } @Override //重写获取年薪的方法 //因为普通员工没有其他收入,则直接调用父类方法 不用添加别的东西 public double getAnnual() { return super.getAnnual(); } }
package com.hspedu.poly_.polyaraneter_; //经理类 public class Manager extends Employee{ //经理类独有的属性 private double bonus; //构造器 public Manager(String name, double salary, double bonus) { super(name, salary); this.bonus = bonus; } //get set 方法 public double getBonus() { return bonus; } public void setBonus(double bonus) { this.bonus = bonus; } public void manger() { System.out.println(" 经理 " + getName() + " 正在划水 "); } //重写获取年薪的方法 //因为经理多了一个奖金的收入 故在原先的基础上 + bonus @Override public double getAnnual() { return super.getAnnual() + bonus; } }
标签:salary,name,bonus,double,void,练习,多态,参数,public From: https://www.cnblogs.com/shuqiqi/p/17029110.html