0

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

4

2 回答 2

1

arr数组中的第二个元素是A使用无参数构造函数初始化的类型对象

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

你调用f(2)那个对象。这将是A#f(int)方法(即f()您的A类中的方法)

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

因此,您将 2 加到 1,即。3.


似乎你的意思是第一个元素。第一个元素使用无参数B构造函数初始化

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

它调用A构造函数

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

设置_x3. 当您调用f(2)此对象时,由于多态性和后期绑定,它会调用f(int)方法。B

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

这将删除 2 到 3,即。1. 但是super.f(x)将调用将 2 添加回A的版本,即。的最终结果是 3。f(int)_x_x

于 2013-11-12T19:21:49.033 回答
0

第一个元素是 的一个实例B。默认构造函数被调用,它调用super(3);. _x然后将等于 3。循环的第一次迭代将是arr[0].f(2);this 将调用fin 中的方法B。这将减少_x2,因此 3-2=1。f然后调用超级-> 1 + 2 = 3。

于 2013-11-12T19:34:51.563 回答