• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors & methods

 
Vijayakumar Ramakrishnan
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
Please help me with this problem..The output is 22..Please explain !!
Vandanam
vijay

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 TestThread3 {
public static void main(String args[]) {
bogo(new Extension());
}
static void bogo(Base b) {
b.add(8);
b.print();
}
}
 
Aru Ven
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vijay,
Here are the steps...

1. When line 1 is executed
bogo(Extension());
First the constructor is fired. Since the constructors follow hierarchy. The Base class (which is the super class of Extension)
constructor will be called.
2. In the Base class constructor the method add(1) is called. So the add method of the Extension is called.
i += v*2; // i = 0+(1*2) = 2 ; i = 2
So i = 2 here.
3. Now the Extension constructor will be executed. In which again is a call to the add method. add(2)
i += v*2; // i = 2 + (2 * 2) = 6 ;
So i = 6 here.
4. So now the method bogo is called with Extension( //1)
b.add(8) // 4
i += v*2; // i = 6 + (8 * 2) = 6 + 16
i = 22 ;
5. So when the print method is called. It will print 22.

HTH,
Aruna
 
Rajpal Kandhari
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Aru,
I compiled and run the program code given by VijayaKumar and got the same output of i=22.
I am aware of the fact that the child class constructor will implicitly call parent class no argument constructor. And this is happening here. That is Extension() constructor is calling Base() constructor which is calling add(1) method. Here is my problem. How is Parent (Base) class Constructor looks down in its child (Extension) class add(int) method. Why it didn't went for add(int) method of Base class.
I am finding this as trick part in the given code.
Aru, please highlight on it.
Thanks , regards,
Raj.
ok fine i can think of this much: at runtime add(int) method is invoked based on the type of object which is calling it....right..
But can we restric it some how to only go for add(int) method of the Base class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic