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

Stranger super()

 
Michael Lin
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer should be 22, not 21
 
Cherry Mathew
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 141
Java Redhat Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI Sasi,Cherry,
You cleared a very Important concept .
I always got stumped when I got a question like this.
Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic