user3271698
user3271698

Reputation: 145

Inheritance issue that i cannot understand

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

Upvotes: 1

Views: 77

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213193

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.

Upvotes: 6

Related Questions