从子类更改超类实例变量

1 java inheritance subclass superclass

我完成了这项任务,但我还不太清楚如何解决它:“更改与C类相关的所有三个x变量。”

class A {
    public int x;
}

class B extends A {
    public int x;
}

class C extends B {
    public int x;

    public void test() {
        //There are two ways to put x in C from the method test():
        x = 10;
        this.x = 20;

        //There are to ways to put x in B from the method test():
        ---- //Let's call this Bx1 for good measure.
        ---- //Bx2

        //There is one way to put x in A from the method test();
        ---- //Ax1
    }
}
Run Code Online (Sandbox Code Playgroud)

为了测试,我设置了这个:

public class test {
    public static void main(String[] args)
    {
        C c1=new C();
        c1.test();
        System.out.println(c1.x);

        B b1=new B();
        System.out.println(b1.x);

        A a1=new A();
        System.out.println(a1.x);
    }
}
Run Code Online (Sandbox Code Playgroud)

得出20、0、0。

现在,我发现我可以这样写Bx1

super.x=10;
Run Code Online (Sandbox Code Playgroud)

这将改变xB,但我无法弄清楚如何调用它在我的test.java

你如何获得Bx1Bx2Ax1,你怎么称呼他们为测试?

T.J*_*der 5

可以x使用超类类型引用访问超类的版本:

System.out.println("A's x is " + ((A)this).x);
Run Code Online (Sandbox Code Playgroud)

那会得到A#x

但是总的来说,隐藏超类的公共实例成员是一个非常糟糕的主意。

示例:IDEOne上的实时副本

class Example
{
    public static void main (String[] args) throws java.lang.Exception
    {
        new C().test();
    }
}

class A {
    public int x = 1;
}

class B extends A {
    public int x = 2;
}

class C extends B {
    public int x = 3;

    public void test() {
        //There are two ways to put x in C from the method test():
        System.out.println("(Before) A.x = " + ((A)this).x);
        System.out.println("(Before) B.x = " + ((B)this).x);
        System.out.println("(Before) C.x = " + this.x);
        ((A)this).x = 4;
        System.out.println("(After) A.x = " + ((A)this).x);
        System.out.println("(After) B.x = " + ((B)this).x);
        System.out.println("(After) C.x = " + this.x);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

(之前)Ax = 1
(之前)Bx = 2
(之前)Cx = 3
(之后)Ax = 4
(之后)Bx = 2
(之后)Cx = 3