首先通过代码来分析一下:
先定义一个Employee的超类,然后定义一个Manager类型的子类,继承于该超类,代码如下:
public class Employee {
private String name;
private double salary;
private LocalDate hireDay;
Employee(){}
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 LocalDate getHireDay() {
return hireDay;
}
public void setHireDay(LocalDate hireDay) {
this.hireDay = hireDay;
}
public Employee(String name, double salary ,int year,int month,int day) {
this.name = name ;
this.salary = salary;
hireDay = LocalDate.of(year, month, day);
}
public class Manager extends Employee{
private double bouns;
public Manager(String name, double salary, int year, int month, int day) {
super(name, salary, year, month, day);
bouns = 0;
}
public double getSalary() {
double baseSalary = super.getSalary();
return baseSalary + bouns;
}
public void setBonus(double b) {
bouns = b;
}
}
public class ManagetText {
public static void main(String[] args) {
Manager boss = new Manager("aaa",8000,1999, 9,2);
boss.setBonus(200);
Employee [] staff = new Employee[3];
staff[0] = boss;
staff[1] = new Employee("sdsa", 3000, 2000, 2, 2);
staff[2] = new Employee("sdsa", 3000, 2000, 2, 2);
for( Employee s :staff ) {
System.out.println(s.getName()+" "+ s.getSalary());
}
}
}
结果:
aaa 8200.0
sdsa 3000.0
sdsa 3000.0
将子类对象赋值给超类对象时,超类对象仅仅接受自己所包含的成员变量的值或成员方法。就比如上面的例子中,staff[0] = boss; 但是staff[0]声明的是Employee类型的,它不能访问Manager类型对象所独有的方法,比如说setBouns()方法,staff[0]是没有访问权限的。这造成了对象数据的丢失。
但是如果将staff声明成Manager类型,这样就可以避免数据的损失。
这种问题在类的继承中 比较常见,并且在之后的工厂方法中也是非常重要的技术要点!!!
参考;《java核心技术卷一》