posted 19 years ago
Instance methods are chosen dynamically at run time based on the type of the actual object on which the method is called. In this case, the actual object is of type B. Your guess that the output would include "this is returnI() of B" shows that you knew that fact. Within the returnI() method in class B, the instance variable i (of class B) is within scope, so the method can return a copy of that variable's value without a problem. From the point of view of that method, i is a variable whose value is 20. The method is able to return a copy of that value.
Note that a.returnI() is not accessing the i instance variable directly. Instead, it is calling the returnI() method of an object of type B. Within that method, i refers to the variable in the same class as the method, which equals 20. So when the method returns the value of i, it returns 20.
As you correctly surmised, the value of a.i is 10, since instance variables accessed directly via the dot operator (.) are selected based on the type of the reference variable, not the type of the actual object. In this case, the reference variable is of type A, so the value of a.i is 10.
SCJA 1.0 (98%), SCJP 1.4 (98%)