说我有以下代码:
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时,我得到变量而不是对象的行为.这是为什么?
这篇博客探讨了Java中类的继承和多态性。通过示例代码展示了Employee和Manager类的关系,以及如何实例化对象。当使用Employee类型的引用指向Manager对象时,调用getDetails()方法表现出多态性,但访问salary属性时,由于向上转型,显示的是Employee类的salary(2000),而非Manager类的(5000)。这体现了Java中成员变量的静态绑定特性。

486

被折叠的 条评论
为什么被折叠?



