File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructors & methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructors & methods" Watch "Constructors & methods" New topic
Author

Constructors & methods

Vijayakumar Ramakrishnan
Greenhorn

Joined: Dec 16, 2000
Posts: 24
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

Joined: Sep 28, 2000
Posts: 199
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

Joined: Aug 26, 2000
Posts: 126
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.


Regards,<P>Raj.<BR>-------------------------<BR>Afforts should be Appriciated.<BR>-------------------------
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Constructors & methods