Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why do we get 40?

 
kishore kovil
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 one
{
public static void main(String arg[])
{
Base b=new Derived();
System.out.println(b.getValue());
}
}
 
kishore kovil
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and 30 when the methods are static?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please edit your post and put tags around your program.

To avoid confusion please modify your program to have the methods you want to be static and make sure it compiles and runs first.
[ December 22, 2006: Message edited by: Barry Gaunt ]
 
Rick Taylor
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kishore,

You can see what's happening if you add a print statement to each of your addValue() method definitions. Try adding:



to the addValue() method in class Derived, and a similar statement in class Base.
 
Anuragk kushwaha
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes...it will print 40.

when object is created in class "one", constructor of derived class gets called. since it is default conctr, it will default constr of it's parent class ie "Base" first without executing addValue().

in base class constr addValue() of "Derived" class(overridden version of addValue) gets called ..
here value =20....after completion of this constr of derived class gets executed where it will call again overridden version of addValue() from derived.......and the vale becomes 40..
........** addValue() method of Base class never executed...
-----
hope this helps.......
 
Prabhu Venkatachalam
Ranch Hand
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you instantiate subclass by calling its constructor, base class default(no args) constructor will also be called.

down the line complier inserts super() keyword if you didn't specify the one.
 
Pankaj Patel
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Really A nice Question.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic