Say I have the following code:
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() {...}
}
and a main()
that does the following:
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?
The book says "you get the behavior associated with the object to which the variable refers at runtime". Ok, I get behavior of Manager class when a method getDetails
is called, but when I access an attribute salary
, I get behavior of variable and not the object. Why is that?