Java Virtual Method Call

Let's 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(), which performs the following actions:

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 behavior associated with the object that the variable belongs to at run time." Ok, I get the behavior of the Manager class when the method is called getDetails, but when I access the attribute salary, I get the behavior of a variable, not an object. Why is this?

+4
source share
4 answers

No field polymorphism. The field in the subclass hides the field with the same name in the superclass, but if you use a variable of the superclass type - Employee- to access the field, you get the superclass field.

, . , .

, , getter setter. getter setter , , .

public class Employee
{
    private int salary = 2000;
    public void getSalary() {
        return salary;
    }
}

public class Manager extends Employee
{
    private int salary = 5000;
    @Override
    public void getSalary () {
        return salary;
    }
}

...

Employee emp_new = new Manager();
System.out.println(emp_new.getSalary()); // will print 5000
+6

- .

JLS 8.3.

, , , .

(§8.4.8.3), , .

(§6.5.6.2), , , super (§15.11.2) .

, salary, Employee Manager ( ).

, Employee hidden salary Employee class salary.

+2

A class Employeeis a class parent, and called attributes return the value of the parent attributes (since they have the same name and type).

0
source

Because it is NOT Virtual Method Invocation.

As noted:

you get behavior associated with the object the variable belongs to at run time

You have overlooked that a variable is salaryNOT part of the behavior - it is an object state.

0
source

Source: https://habr.com/ru/post/1589149/


All Articles