【问题标题】:Inheritance issue that i cannot understand我无法理解的继承问题
【发布时间】:2014-02-08 23:57:49
【问题描述】:

我有这两个课程:

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

【问题讨论】:

  • 您介意让整个示例合理吗?我不介意阅读本身非常令人麻木的代码,但是阅读半混淆的变量/类名很快就会变得烦人。同时添加@Override标签。
  • 把脑子里的代码过一遍就好了……不调用超级构造函数的时候,调用的是空的超级构造函数。
  • 把每一步都写在纸上。请记住,如果构造函数没有显式调用 super(),它要做的第一件事就是调用不带参数的超级构造函数。
  • @JB Nizet,除非你用参数调用其他一些超级构造函数。
  • 是的,当然。解决了这个问题。

标签: java inheritance


【解决方案1】:

构造函数:

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

被编译器翻译成这样:

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

我想你现在应该明白了,为什么是6

【讨论】:

  • 在第一个 super _x = 1 之后,然后我有 super.f(x) 所以它转到 A 类中的 f 函数,但是因为我在 B 类中有函数,它从 B 实现 f类,在这个 f 里面我有另一个时间 super.f(x) 所以它看起来像递归
  • @user3271698 super.f(x) 不会调用被覆盖的方法。
  • 为什么不呢?它的 B 对象
  • 因为super.f(x)准确的意思是:调用f()方法的超类实现。
猜你喜欢
  • 1970-01-01
  • 2014-11-10
  • 2017-01-01
  • 2015-02-07
  • 1970-01-01
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多