从子类更改超类实例变量

时间:2015-10-15 14:05:14

标签: 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
    }
}

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

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);
    }
}

其中20,0,0。

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

super.x=10;

这会改变x中的B,但我无法弄清楚如何在test.java中调用它。

如何获得Bx1Bx2Ax1,以及如何将其称为测试?

3 个答案:

答案 0 :(得分:4)

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

System.out.println("A's x is " + ((A)this).x);

这将获得A#x

但总的来说,影响超类的公共实例成员是一个非常的坏主意。

示例:live copy on 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);
    }
}

输出:

(Before) A.x = 1
(Before) B.x = 2
(Before) C.x = 3
(After) A.x = 4
(After) B.x = 2
(After) C.x = 3

答案 1 :(得分:0)

这是您的测试方法的样子

void test() {
    this.x = 30;
    A a = this;
    a.x = 10;
    B b = this;
    b.x = 20;
}

重要的是要注意,您正在访问您定义的类的类型的变量,因此在这种情况下,您将从x和{{1}访问,A通过x关键字定义变量,从B开始。

答案 2 :(得分:0)

使用 getters and setters

A级{

public int x;

}

B类延伸A {

public int x;

public void setAx(int x) {
    super.x = x;
}
public int getAx() {
    return super.x;
}

}

C类延伸B {

public int x;

public void test() {

    x = 10;
    this.x = 20;

}
public void setBx(int x){
    super.x = x;
}
public int getBx() {
    return super.x;
}

public static void main(String[] args)
{
    C c1= new C();
    c1.x = 1;
    c1.setAx(2);
    c1.setBx(3);

    System.out.println(c1.getAx()+"/"+c1.getBx()+"/"+c1.x);
}

}