The most intelligent Java IDE
[Logo] JavaRanch » Big Moose Saloon
  Search | FAQ | Recent Topics | Hot Topics
Register / Login


Reply Bookmark it! Watch this topic JavaRanch » Forums » Professional Certification » Programmer Certification (SCJP)
 
RSS feed
 
New topic
Author

why the overridden method is called?

Anuradha Prasanna
Ranch Hand

Joined: Mar 09, 2006
Messages: 88



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?

SCJP 6.0 90%
Wouter Oet
Ranch Hand

Joined: Oct 25, 2008
Messages: 501

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.

"Any fool can write code that a computer can understand.
Good programmers write code that humans can understand." --- Martin Fowler
Velu Kasirajah
Greenhorn

Joined: Feb 06, 2010
Messages: 15

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

Velu Kasirajah
Anuradha Prasanna
Ranch Hand

Joined: Mar 09, 2006
Messages: 88

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.

SCJP 6.0 90%
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Messages: 2328

Velu Kasirajah wrote:It's due to method overriding (hiding).

Overriding is not a Hiding. both are different things.
OverridingVsHiding
another Link

How to Ask Good Question|EL or JSTL problem|Tomcat Faq
Vivek K Singh
Ranch Hand

Joined: Dec 22, 2009
Messages: 74

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.


SCJP 6
 
 
 
Reply Bookmark it! Watch this topic JavaRanch » Forums » Professional Certification » Programmer Certification (SCJP)
 
RSS feed
 
New topic
JProfiler
Get rid of your performance problems and memory leaks!