wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes initialisation & control flow Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "initialisation & control flow " Watch "initialisation & control flow " New topic
Author

initialisation & control flow

basha khan
Ranch Hand

Joined: Jan 18, 2002
Posts: 87
just look the code
What will this program print out ?
--------------------------------------------------
class Base{
int value = 0;
Base(){
addValue();
}
void addValue(){
value += 10;
}
int getValue(){
return value;
}
}
class Derived extends Base{
Derived(){
addValue();
}
void addValue(){
value += 20;
}
}
public class Test3 {
public static void main(String[] args){
Base b = new Derived();
System.out.println(b.getValue());
}
}
--------------------------------------------------
it prints 40.why the answer is 40 instead of 30.
plz explain me the conrol flow.
wishing a nice day to everybody..
R K Singh
Ranch Hand

Joined: Oct 15, 2001
Posts: 5371
Good example of overriding
HTH


"Thanks to Indian media who has over the period of time swiped out intellectual taste from mass Indian population." - Chetan Parekh
Younes Essouabni
Ranch Hand

Joined: Jan 13, 2002
Posts: 479
Base b = new Derived();
You construct an object Derived with the constructor of Base.
So when you do b.method() the compiler check if the method exist in Base:
- If not compil error.
- If Yes compiler check if it exist in subclass(Derived):- If no, use Base method(getValue())
-If yes, use subclass method.
So each time you call getValue() on a Derived object, you do +20.
Hope I was clear.


Younes
By constantly trying one ends up succeeding. Thus: the more one fails the more one has a chance to succeed.
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
basha,
We'd like to read the Javaranch Naming Policy and register again.
Thank you for your cooperation.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944

This instruction creates an object of the class Derived. JVM first call the constructor in the Base class:

This constructor calls the addValue method of the Derived class because this method is overiden:

Then JVM calls the Derived's constructor that calls the addValue method too. Again it calls the Derived's addValue method:

value is incremented twice by 20.
[ January 25, 2002: Message edited by: Carlos R Ram�rez ]
 
GeeCON Prague 2014
 
subject: initialisation & control flow