File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructors & methods" Watch "Constructors & methods" New topic

Constructors & methods

Vijayakumar Ramakrishnan

Joined: Dec 16, 2000
Posts: 24
Hi all,
Please help me with this problem..The output is 22..Please explain !!

class Base {
int i;
Base() {
void add(int v) {
i += v;
void print() {
class Extension extends Base {
Extension() {
void add(int v) {
i += v*2;
public class TestThread3 {
public static void main(String args[]) {
bogo(new Extension());
static void bogo(Base b) {
Aru Ven
Ranch Hand

Joined: Sep 28, 2000
Posts: 199
Here are the steps...

1. When line 1 is executed
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.

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,
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:
subject: Constructors & methods
It's not a secret anymore!