假设我有以下代码:
public class Employee
{
public int salary = 2000;
public void getDetails() {...}
}
public class Manager extends Employee
{
public int salary = 5000;
public int allowance = 8000;
public void getDetails() {...}
}
还需要一个 main()
函数,它执行以下操作:
Employee emp = new Employee();
Manager man = new Manager();
emp.getDetails(); // method of Employee called, output ok.
man.getDetails(); // method of Manager called, output ok.
Employee emp_new = new Manager();
emp_new.getDetails(); // method of Manager called, ok.
System.out.println(emp_new.allowance); // problem, as Employee doesn't know about allowance. Ok
// the problem
System.out.println(emp_new.salary); // why 2000 and not 5000?
这本书中提到:“在运行时,您将获得与变量引用的对象相关联的行为”。当我调用方法getDetails
时,我了解了Manager类的行为,但是当我访问属性salary
时,我获得的是变量而不是对象的行为。为什么会这样呢?