super 只高一级吗?

does super only go one level above?

如果我有:

class Zero {
    int n = 0;

    void setN(int x) {
        n += x;
    }
}

class One extends Zero {
    int n = 1;

    void setN(int x) {
        n += x;
        super.setN(x);
    }

}

class Two extends One {
    int n = 2;

    void setN(int x) {
        n += x;
        super.setN(x);
    }

    void show() {
        System.out.println(n);
        System.out.println(super.n);
        // System.out.println(super.super.n);   error

    }

    public static void main(String[] args) {
        Two two = new Two();
        two.show();
        // >>>
        // 2
        // 1

        two.setN(1);
        two.show();
        // >>>
        // 3
        // 2
    }
}

我重新编辑了它,方法是 setNZero 传下来的。它起作用了,这是否意味着我仍然可以 'change' Zero 中的 n,但我就是看不到它?

也很有意思,虽然setNOneTwo中完全一样,但我必须手动覆盖它,如果我删除setNTwo 中,这会有所不同。 setN 不会更改 Two 中的 n

好像super只能往上一层?有没有办法把 n 归零?

但另一个问题是,如果我打算在子类中覆盖 int n,为什么它允许我访问父类中的 n

谢谢,

super 不能升两级。它也可以与参数一起使用。作为 super(argument1) 并且它将调用接受 1 个 argument1 类型参数(如果存在)的构造函数。

它也可以用来调用父类的方法。 super.method()

更多信息可以参考here

你可以,但是在 Two.main():

   Two two = new Two();
   Zero z = (Zero)two;
   System.out.println( Zero's n is " + z.n );

这在 Java 中是不可能的,这与 C++ 不同,C++ 使用作用域解析来支持它。

你可以有一个方法

int getZeroN(){
    return n;
}

在您的 Zero 中,然后使用 Two

中的 System.out.println(super.getZeroN()); 调用它