Hi Everyone,
Take a look at this code:
What should the output be ? I thought it was 13.
According to my logic, in the main method, first an instance of Sub() is created. This calls the Sub() constructor. But since Sub extends Base, so the Base() constructor is called first.
Now the base function add() is called with argument 1 as add(1) and hence i gets the value 1.
The call returns back to Sub() where add(2) is called. Since i is already 1, so in Sub(), we get i += v*2 as 1 + 2*2 which is 5.
Finally the control comes back to bogo() where b.add(8) is called. Since the type of object passed is Base type, so the base class add is called here which gives i as i = 5 + 8 which is 13.
But the correct answer is 22.
Can anybody explain why my logic was wrong and what the correct logic is ?
Thanks
alot