【发布时间】:2015-05-21 07:39:22
【问题描述】:
假设我有以下代码:
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?
这本书说“你会得到与变量在运行时引用的对象相关的行为”。好的,当调用 method getDetails 时,我得到了 Manager 类的行为,但是当我访问属性 salary 时,我得到的是变量而不是对象的行为。这是为什么呢?
【问题讨论】:
标签: java polymorphism