2014-02-08 46 views
1

我有这2类:继承问题,我无法理解

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

输出为3 3 6,我不知道为什么第三次迭代是6

+1

使用调试器。 –

+1

你介意让整个例子有点合理吗?我不介意阅读本身非常麻烦的代码,但是阅读半混淆的变量/类名称会很快变得烦人。还要添加'@ Override'标签。 – skiwi

+0

只需仔细阅读您的想法中的代码......当您不调用超级构造函数时,将调用空的超级构造函数。 – Matthias

回答

6

构造函数:

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

被编译器翻译为:

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

我想现在你会明白,为什么它是6

+0

后第一个超级_x = 1,之后,我有super.f(x),所以它去f类函数内的A类,但因为我有在B类的功能它实现f从B类和这个fi内有另一个time super.f(x)所以它看起来像递归 – user3271698

+0

@ user3271698'super.f(x)'不会调用重写的方法。 –

+0

为什么不呢?它的B对象 – user3271698