1

I have this 2 classes:

public class A {
    protected int _x;

    public A() {
        _x = 1;
    }

    public A(int x) {
        _x = x;
    }

    public void f(int x) {
        _x += x;
    }

    public String toString() {
        return "" + _x;
    }
}
public class B extends A {
    public B() {
        super(3);
    }

    public B(int x) {
        super.f(x);
        f(x);
    }

    public void f(int x) {
        _x -= x;
        super.f(x);
    }

    public static void main(String[] args) {
        A[] arr = new A[3];
        arr[0] = new B();
        arr[1] = new A();
        arr[2] = new B(5);
        for (int i = 0; i < arr.length; i++) {
            arr[i].f(2);
            System.out.print(arr[i] + " ");
        }
    }
}

The output is 3 3 6 and I am wonder why the third iteration is 6

5
  • 1
    Would you mind making the whole example somewhat reasonble? I do not mind reading code that itself is quite mind-numbling, however reading half-obfuscated variable/class names gets annoying quickly. Also add @Override tags. Commented Feb 8, 2014 at 15:04
  • Just go through the code in your mind... When you do not call a super constructor, the empty super constructor is called. Commented Feb 8, 2014 at 15:05
  • 1
    Write each step on paper. Remember that the first thing a constructor does if it doesn't explicitely invoke super() is to invoke the super constructor without argument. Commented Feb 8, 2014 at 15:05
  • @JB Nizet, except you call some other super constructor with arguments. Commented Feb 8, 2014 at 15:06
  • Yes, of course. Fixed that. Commented Feb 8, 2014 at 15:07

1 Answer 1

6

The constructor:

public B(int x)
{
    super.f(x);
    f(x);
}

is translated by the compiler to this:

public B(int x)
{
    super();
    super.f(x);
    f(x);
}

I guess now you would understand, why it's 6.

Sign up to request clarification or add additional context in comments.

4 Comments

after the first super _x = 1, and after that i have super.f(x) so it goes to f function inside A class but because i have the function inside B class it implement f from B class and inside this f i have another time super.f(x) so it looks like recursion
@user3271698 super.f(x) won't call the overridden method.
Why not ? its B object
Because super.f(x) precisely means: call the superclass implementation of the f() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.