<code>
What will be the result of the following code?
1. class Base {
2. int i;
3. Base(){
4. add(1);
5. }
6. void add(int v){
7. i+=v;
8.
9. }
10. void print(){
11. System.out.println(i);
12. }
13. }
14.
15. class Extension extends Base{
16. Extension(){
17. add(2);
18. }
19. void add(int v){
20. i+=v*2;
21.
22. }
23. }
24.
25. public class Test6{
26.
27. public static void main(
String[] args){
28. bogo(new Extension());
29.
30. }
31. static void bogo(Base b){
32. b.add(8);
33. b.print();
34.
35. }
}
</code>
I dont remember the answers but I compiled and found the answer to be 22. I may have some fundamental doubt here since I would think that
a.
line#28 would cause the variable i to have a value 1 (see
line#7) when it is constructed via an implicit call to the default constructor of the Base class but instead it is having a value 2. (I printed out the value of i at line #8 in a separate program).
b.
line#28 would cause the variable i to have a value 5
after i+=v*2; (see
line#20) when the Extension class is constructed but instead it is having a value 6. (I printed out the value of i at line #8 in a separate program).
c.
line#32 would cause the variable i to have a value 21
after i+=v*2; (see
line#20) when it will call the b.add(8) in
line#32 but instead it is having a value 22. (I printed out the value of i at line #8 in a separate program).
My question is . If I have a method :
void aMethod(int v){
i+=v;
} where i is a class member variable int i.
Does the passing of an argument b.aMethod(1) change the value of both i and v to 1? If so, why line#32 does not cause b.add(8) to have the result 24 instead of 22 i.e (i = 8 + 8*2) whereas line #4 add(1) and line#17 add(2) gives result (i=1+1=2) and (i=2+2*2=6) respectively.
I have no other doubts regarding latebinding etc. I hope I could be clear enough.
[This message has been edited by Howard Stern (edited April 25, 2000).]
[This message has been edited by Howard Stern (edited April 26, 2000).]