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