• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

initialisation & control flow

 
basha khan
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good example of overriding
HTH
 
Younes Essouabni
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
basha,
We'd like to read the Javaranch Naming Policy and register again.
Thank you for your cooperation.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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 ]
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic