gpt4 book ai didi

java - 在父项和子项中初始化一个实例变量

转载 作者:搜寻专家 更新时间:2023-11-01 02:04:23 25 4
gpt4 key购买 nike

我有以下 Java 代码

public class Base {
private static boolean goo = true;

protected static boolean foo() {
goo = !goo;
return goo;
}

public String bar = "Base:" + foo();

public static void main(String[] args) {
Base base = new Sub();
System.out.println(base.bar);
}
}

public class Sub extends Base {
public String bar = "Sub:" + foo();
}

我被问到它会打印什么。经过测试,答案似乎是 Base:false,但我真的无法理解为什么不是 Sub:true

在最终打印上使用断点运行调试器,我有以下对象: Debugger base

显示 base 有两个同名变量!一个印有 Base:false,另一个印有(我)预期的 Sub:true。确实 foo() 被调用了两次,但每次都实例化了一个不同的变量?子类中创建的同名变量(并在第一个创建后初始化)不应该覆盖父类中的变量吗? Java 如何选择打印哪一个?

最佳答案

...which shows base having two variables with the same name!

是的! base 是对 Sub 实例的引用,Sub 实例有两个 bar 字段。我们称它们为 Base$barSub$bar:

        +------------------------+base--->|      Sub instance      |        +------------------------+        | Base$bar: "Base:false" |        | Sub$bar:  "Sub:true"   |        +------------------------+

Java allows for the same name being used at different levels in an instance's type hierarchy. (It has to: Frequently these are private fields, and so a subclass may not even know that the superclass has one with the same name.)

Those two different fields in the instance have different values: Base$bar has the value Base:false because it's initialized based on the first-ever call to foo, which flips goo (which starts as true) and uses the flipped result. Sub$bar has the value Sub:true because it's initialized from the second-ever call to foo, so goo is flipped again and the updated value is used. There is only one instance created, but foo is called twice.

Which bar you see when you access bar depends on the type of the reference you have to the instance. Because base is declared of type Base, when you do base.bar you access the Base$bar field in the Sub instance. If you had a Sub reference to the instance, you'd access Sub$bar instead:

System.out.println(base.bar);        // "Base:false"
System.out.println(((Sub)base).bar); // "Sub:true"

Live Example

关于java - 在父项和子项中初始化一个实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38179774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com