gpt4 book ai didi

java - 为什么字段似乎在构造函数之前被初始化?

转载 作者:IT老高 更新时间:2023-10-28 20:32:35 26 4
gpt4 key购买 nike

public class Dog {

public static Dog dog = new Dog();
static final int val1 = -5;
static int val2 = 3;
public int val3;

public Dog() {
val3 = val1 + val2;
}

public static void main(String[] args) {
System.out.println(Dog.dog.val3);
}
}

输出是-5

从这个结果看来,val2 的初始化似乎是在 dog 成员及其实例化完成之前。

为什么这个顺序是这样的?

最佳答案

如果你最后移动你的狗实例,你可能会发现输出变成-2

public class Dog {

static final int val1 = -5;// This is final, so will be initialized at compile time
static int val2 = 3;
public int val3;

public static Dog dog = new Dog();//move to here

public Dog() {
val3 = val1 + val2;
}

public static void main(String[] args) {
System.out.println(Dog.dog.val3);//output will be -2
}
}

最终的字段(其值为编译时常量表达式)将首先被初始化,然后其余的将按文本顺序执行。

因此,在您初始化狗实例的情况下, static int val2(0) 尚未初始化,而 static final int val1(-5) 则自这是最终的。

http://docs.oracle.com/javase/specs/jls/se5.0/html/execution.html#12.4.2声明:

execute either the class variable initializers and staticinitializers of the class, or the field initializers of the interface,in textual order, as though they were a single block, except thatfinal class variables and fields of interfaces whose values arecompile-time constants are initialized first


更新了一个较新的文档

这里是 http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.2 中的 jdk7 版本

final 字段在第 6 步:

Then, initialize the final class variables and fields of interfaceswhose values are compile-time constant expressions

当静态字段在第 9 步时:

Next, execute either the class variable initializers and staticinitializers of the class, or the field initializers of the interface,in textual order, as though they were a single block.

关于java - 为什么字段似乎在构造函数之前被初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27394945/

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