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

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;
void addValue(){
value += 10;
int getValue(){
return value;
class Derived extends Base{
void addValue(){
value += 20;
public class Test3 {
public static void main(String[] args){
Base b = new Derived();
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: 5382
Good example of overriding

"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.

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

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

[Blog] [Blogroll] [My Reviews] My Linked In
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 ]
I agree. Here's the link: http://aspose.com/file-tools
subject: initialisation & control flow
It's not a secret anymore!