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



我想咨询有关 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)?

它们共享相同的地址,但是您确实用1覆盖了默认值0,因此这是正确的行为。让我们检查一下:

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

你会在最后一行得到一个异常,因为类 son 不包含字段a

它是同一个,因为Son没有自己的a。如果你引入一个,你将隐藏Parenta,然后你会看到你期望的行为:

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

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

最新更新