wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Stranger super() 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 "Stranger super()" Watch "Stranger super()" New topic
Author

Stranger super()

Michael Lin
Ranch Hand

Joined: Dec 04, 2000
Posts: 31
can anyone explain the following strange result??
Thanks,
class Base {
int i;
Base() {add(1);}
void add(int v) {i += v;}
void print() {System.out.println(i);}
}
class Extension extends Base {
Extension() {add(2);}
void add(int v) {
i += v*2;
}
}
public class Arg {
public static void main(String args[]) {
bogo(new Extension());
}
static void bogo(Base b) {
b.add(8);
b.print();
}
}
sasi dhulipala
Ranch Hand

Joined: Dec 28, 2000
Posts: 31
Michael,
It is like this
When we say new Extension()
First it calls its own Constructor which in turn calls
its base class contructor, when it finds add fn in the base class
constructor the add fn inside Extension class is called.
remember the method calling is dependent on the object of
reference at run time. Here the derived class reference is passed hence add fn inside Extension isd called. From then onwards it is simple program flow which goes on like:
i = 0; default
i += (v=1) *2 // add fn inside Extension
>> i =2;
again add(v) inside Extension Constructor.
i (2) += v(2)*2;
>>i =6;
Now inside bogo another add(8) is there this results in
i += v(8)*2
= 6 +16
= 22
inside bogo once we call print it prints 22 as out put.
HTH
sasi


[This message has been edited by sasi dhulipala (edited January 11, 2001).]
golu jain
Greenhorn

Joined: Jan 10, 2001
Posts: 19
Hi !
The answer should be 21.
[This message has been edited by golu jain (edited January 11, 2001).]
[This message has been edited by golu jain (edited January 11, 2001).]
Jeffrey Lee
Greenhorn

Joined: Dec 29, 2000
Posts: 2
The answer should be 22, not 21
Cherry Mathew
Ranch Hand

Joined: Dec 26, 2000
Posts: 159
I got this wrong when i first saw it
we get this wrong bcoz we still think linearily now we got to think in OOPs way
whenever a non-static method is called we got to check the object hierachy and see whther the method was overridden if it is overridden somewhere the overridden method will be called.
Dont get confused bcoz the method is there in the super class
The answer is 22
Cherry
sunil choudhary
Ranch Hand

Joined: Nov 10, 2000
Posts: 141

HI Sasi,Cherry,
You cleared a very Important concept .
I always got stumped when I got a question like this.
Thanks.

"Learning is weightless, a treasure you can always carry easily." -Chinese Proverb
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Stranger super()
 
Similar Threads
Another question
Constructors & methods
program output
Constructor Problem
How to read this program?