简体   繁体   中英

Why can't we use child only method for array declared as parent class type, with element containing child class reference?

Having the three following classes:

Main class

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);

  }

}

Employee class (parent class)

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;

  }

}

Boss class (child class)

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;

  }

}

My question is as follows. Why do we need to cast myEmployees [3] to a Boss class and store its value in a Boss variable, before we are allowed to use a Boss only method?

I understand that the array myEmployees was declared as an array containing references to Employee objects, but as myEmployees can hold a Boss objects references (due to the Liskov substitution principle), the reference of myEmployees [3] is actually to a Boss object. Why the setBonus method cannot be used on myEmployees [3] directly if it's holding a reference to a Boss object?

按照设计,它是通过子类覆盖超类方法,而不是相反。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM