aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why do we get 40? 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 "why do we get 40?" Watch "why do we get 40?" New topic
Author

why do we get 40?

kishore kovil
Greenhorn

Joined: Dec 21, 2006
Posts: 20
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

Joined: Dec 21, 2006
Posts: 20
and 30 when the methods are static?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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 ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Rick Taylor
Greenhorn

Joined: Oct 10, 2006
Posts: 12
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.


Rick Taylor
Anuragk kushwaha
Ranch Hand

Joined: Aug 02, 2006
Posts: 51
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

Joined: Nov 16, 2005
Posts: 502

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.


Prabhu Venkatachalam<br />SCJP 1.4,SCWCD 1.4<br />prabhu.venkatachalam@gmail.com
Pankaj Patel
Ranch Hand

Joined: Jul 13, 2006
Posts: 73
Really A nice Question.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why do we get 40?