output:
Extension add(int v) i 2
Extension add(int v) i 6
Extension add(int v) i 22
22
In the above program, after line 1, line 2 should be called(add(int v)method of Base class), but instead line 3 is called(add(int v) of Extension class). i dont understand why line 3 is called instead of line 2?
That is called polymorphism. It is one of the basics of OO programming. It is however not always easy.
There is a lot of info about it on the web. You could start with the javatutorial.
"Any fool can write code that a computer can understand.
Good programmers write code that humans can understand." --- Martin Fowler
It's due to method overriding (hiding). Since both the base and the extended classes have the same method, the one from the extended class will be executed.
Well it is a case of Overriding (run-time polymorphism), I dont see method hiding anywhere. Method hiding will actually stop this type of behaviour.
When the execution starts, new Extension() is called that calls super constructor, but as the add(int) implementation has been oversiden so all add(int) calls will be made to the overriden add(int) method in the Extension class
so you get the output as:
<<initally int i is 0>>
then:
Extension add(int v) i 2 // Coz of the super constructor of Base class -> add() call
Extension add(int v) i 6 // Coz of the constructor of Extension class -> add() call
Extension add(int v) i 22 // Final call made from Qd073 Class
then the value is printed as 22.