方法定义的形参类型为父类类型,实参类型允许为子类类型

案例

  1. 定义员工类Employee,包含姓名和月工资【private】,以及计算年工资getAnnual的方法。普通员工和经理继承了员工,经理类多了奖金bonus属性和管理manage方法,普通员工多了work方法,普通员工和经理要求分别重写getAnnual方法。
  2. 测试类中添加一个方法showEmpAnnual(Employee e),实现获取任何员工对象的年工资,并在main方法中调用该方法(e.getAnnual())
  3. 测试类中添加一个方法,testWork,如果是普通员工,则调用work方法,如果是经理,则调用manage方法。

image.png

Employee

  1. package test;
  2. public class Employee {
  3. private String name;
  4. private double salary;
  5. public Employee(String name, double salary) {
  6. this.name = name;
  7. this.salary = salary;
  8. }
  9. //得到年工资的方法
  10. public double getAnnual() {
  11. return 12 * salary;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public double getSalary() {
  20. return salary;
  21. }
  22. public void setSalary(double salary) {
  23. this.salary = salary;
  24. }
  25. }

Manager

  1. package test;
  2. public class Manager extends Employee{
  3. private double bonus;
  4. public Manager(String name, double salary, double bonus) {
  5. super(name, salary);
  6. this.bonus = bonus;
  7. }
  8. public double getBonus() {
  9. return bonus;
  10. }
  11. public void setBonus(double bonus) {
  12. this.bonus = bonus;
  13. }
  14. public void manage() {
  15. System.out.println("经理 " + getName() + " is managing");
  16. }
  17. //重写获取年薪方法
  18. @Override
  19. public double getAnnual() {
  20. return super.getAnnual() + bonus;
  21. }
  22. }

Worker

  1. package test;
  2. public class Worker extends Employee {
  3. public Worker(String name, double salary) {
  4. super(name, salary);
  5. }
  6. public void work() {
  7. System.out.println("普通员工 " + getName() + " is working");
  8. }
  9. @Override
  10. public double getAnnual() { //因为普通员工没有其它收入,则直接调用父类方法
  11. return super.getAnnual();
  12. }
  13. }

Main

  1. package test;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Worker tom = new Worker("tom", 2500);
  5. Manager milan = new Manager("milan", 5000, 200000);
  6. Main main = new Main();
  7. main.showEmpAnual(tom);
  8. main.showEmpAnual(milan);
  9. main.testWork(tom);
  10. main.testWork(milan);
  11. }
  12. //showEmpAnnual(Employee e)
  13. //实现获取任何员工对象的年工资,并在main方法中调用该方法 [e.getAnnual()]
  14. public void showEmpAnual(Employee e){
  15. System.out.println(e.getAnnual());//动态绑定机制
  16. }
  17. //添加一个方法,testWork,如果是普通员工,则调用work方法,如果是经理,则调用manage方法
  18. public void testWork(Employee e) {
  19. if(e instanceof Worker) {
  20. ((Worker) e).work();//有向下转型操作
  21. } else if(e instanceof Manager) {
  22. ((Manager) e).manage();//有向下转型操作
  23. } else {
  24. System.out.println("不做处理...");
  25. }
  26. }
  27. }

image.png