Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why the overridden method is called?

 
Anuradha Prasanna
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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?
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
QuoteYourSources

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 java tutorial.
 
Velu Kasirajah
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Velu Kasirajah
 
Anuradha Prasanna
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, i got it now. though it is very confusing sometimes.

This question is from Khalid A.Mughal(A programmer's guide to scjp certification) mock test.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Velu Kasirajah wrote:It's due to method overriding (hiding).

Overriding is not a Hiding. both are different things.
OverridingVsHiding
another Link
 
Vivek K Singh
Ranch Hand
Posts: 85
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic