user2976270
user2976270

Reputation: 105

Inheritance - try to understand how it work

I have these 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);
    }
}

Main:

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] + " ");
    }
}

I am trying to understand why after the first print the result is 3 and not 1 At the beginning the Class A empty constructor is called so _x = 1 And than f(int x) from class B called so _x = _x - 2 so _x = -1 and after call Super.f(x) _x = _x + x ==> 1

Upvotes: 0

Views: 65

Answers (2)

Sionnach733
Sionnach733

Reputation: 4736

The first element is an instance of B. The default constructor is called which calls super(3);. _x will then be equal to 3. The first iteration of the loop will be arr[0].f(2); this will call the f method in B. This will decrement _x by 2, so 3-2=1. Then the super of f is called -> 1 + 2 = 3.

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280168

The second element in your arr array is an object of type A which was initialized with the no argument constructor

arr[1] = new A();
...
public A(){  
    _x = 1;  
}

You call f(2) on that object. This will be the A#f(int) method (ie. the method f() in your A class)

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

you therefore add 2 to 1, ie. 3.


Seems you meant the first element. The first element is initialized with the no arg B constructor

arr[0] = new B();
...
public B() {  
    super(3);  
}

which invokes the A constructor

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

setting _x to 3. When you call f(2) on this object, it invokes the f(int) method in B because of polymorphism and late binding.

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

This will remove 2 to 3, ie. 1. But the super.f(x) will invoke A's version of f(int) adding 2 back to _x, ie. the end result of _x is 3.

Upvotes: 1

Related Questions