为什么我们不能将仅使用child的方法用于声明为父类类型的数组,并且元素包含子类引用?

时间:2017-09-16 16:58:28

标签: java polymorphism

拥有以下三个课程:

主要课程

public class Main {

  public static void main(String [] args) {

    Employee emp1 = new Employee("John");
    Employee emp2 = new Employee("Mich");
    Employee emp3 = new Employee("Will");

    Boss bss1 = new Boss("Jack");

    Employee [] myEmployees = new Employee [4];

    myEmployees [0] = emp1;
    myEmployees [1] = emp2;
    myEmployees [2] = emp3;
    myEmployees [3] = bss1;

    Boss bss2 = (Boss) myEmployees [3];

    bss2.setBonus(500);

  }

}

员工类(父类)

import java.util.GregorianCalendar;
import java.util.Date;

public class Employee {

  private final String name;
  private String department;
  private Date hiringDate;
  private double salary;

  public Employee(String name) {

    this.name = name;
    this.department = "Finance";
    GregorianCalendar calendar = new GregorianCalendar(2017, 7, 31);
    this.hiringDate = calendar.getTime();
    this.salary = 21000;

  }

}

老板班(儿童班)

public class Boss extends Employee {

  private double bonus;

  public Boss(String name) {

    super(name);
    this.bonus = 300;

  }

  public void setBonus(int bonus) {

    this.bonus = bonus;

  }

}

我的问题如下。为什么我们需要将myEmployees [3]转换为Boss类并将其值存储在Boss变量中,然后我们才允许使用Boss only方法?

我理解数组myEmployees被声明为包含对Employee对象的引用的数组,但由于myEmployees可以保存Boss对象引用(由于Liskov替换原则),myEmployees [3]的引用实际上是一个Boss宾语。为什么如果setBonus方法持有对Boss对象的引用,则不能直接在myEmployees [3]上使用它?

1 个答案:

答案 0 :(得分:0)

通过设计,它可以通过子类覆盖超类方法,反之亦然。