jQuery in Action, 3rd edition
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Stranger super()" Watch "Stranger super()" New topic

Stranger super()

Michael Lin
Ranch Hand

Joined: Dec 04, 2000
Posts: 31
can anyone explain the following strange result??
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) {
sasi dhulipala
Ranch Hand

Joined: Dec 28, 2000
Posts: 31
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.

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

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

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

"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()
It's not a secret anymore!