gpt4 book ai didi

java - final 字段的初始化顺序

转载 作者:搜寻专家 更新时间:2023-10-30 19:54:59 24 4
gpt4 key购买 nike

考虑这两个类:

public abstract class Bar {
protected Bar() {
System.out.println(getValue());
}

protected abstract int getValue();
}

public class Foo extends Bar {
private final int i = 20;

public Foo() {
}

@Override
protected int getValue() {
return i;
}

public static void main(String[] args) {
new Foo();
}
}

如果我执行 Foo,输出是 20。

如果我将字段设置为非最终字段,或者如果我在 Foo 构造函数中对其进行初始化,则输出为 0。

我的问题是:final 字段的初始化顺序是什么?JLS 中在哪里描述了这种行为?

我希望找到一些关于 final 字段的特殊规则 here ,但除非我错过了什么,否则不会。

请注意,我知道我永远不应该从构造函数中调用可重写的方法。这不是问题的重点。

最佳答案

你的final int i成员变量是常量:4.12.4. final Variables

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.

这会影响事物的初始化顺序,如 12.4.2. Detailed Initialization Procedure 中所述。 .

关于java - final 字段的初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29010930/

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