子将有自己的字段变量或通过继承共享其父变量?

时间:2017-01-08 09:35:32

标签: java inheritance

我想咨询有关Java字段变量继承的问题。以下是代码段:

//parent
public class Parent {
    protected int a = 0;
}

//son
public class Son extends Parent{
    public void demo(){
        a = 1;
        System.out.println(super.a);
    }
    public static void main(String[] args){
        Son son = new Son();
        son.demo();
    }
}

输出:

1

期望:

0

在我的代码中,子项将继承字段变量a,我们将其称为sonA,并将父项的字段变量a称为parentA

我的问题是sonAparentA是否相同(例如地址是0x1234)?或者它们代表两个不同的变量(例如一个地址0x1234另一个0x5678)?

2 个答案:

答案 0 :(得分:0)

它是同一个,因为Son没有自己的a。如果你介绍一个,你就会隐藏Parent a,然后你会看到你期待的行为:

//parent
public class Parent {
    protected int a = 0;
}

//son
public class Son extends Parent{
    int a = 0; // this hides the Parent field

    public void demo(){
        a = 1; // this accesses the Son field
        System.out.println(super.a); // this accesses the Parent field explicitly
    }
    public static void main(String[] args){
        Son son = new Son();
        son.demo();
    }
}

然而,这通常不是推荐的做法,因为它可能导致很多混乱。

答案 1 :(得分:0)

它们共享相同的地址,但是您使用0覆盖了默认值1,因此这是正确的行为。我们来看看:

Son son = new Son();
Parent parent = new Parent();
Field fieldAParent = parent.getClass().getDeclaredField("a");
Field fieldA = son.getClass().getDeclaredField("a");

你会在最后一行得到一个例外,因为class son不包含字段a