gpt4 book ai didi

java - 为什么我的实例初始化程序 block 可以在声明之前引用一个字段?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:21:59 26 4
gpt4 key购买 nike

我的理解是,您不能在变量声明之前引用它,并且在类主体内但在任何方法之外的所有代码(包括实例初始化器)在构造函数之前按顺序执行对象被创建(异常(exception)是 static 变量和初始化 block ,它们在程序开始时按顺序运行,以初始化整个类)。那么,为什么以下代码会编译(并运行!):

public class WhyIsThisOk {
{ a = 5; } // why is this ok???
int a = 10;

public WhyIsThisOk() {
}

public static void main(String[] args) {
WhyIsThisOk why = new WhyIsThisOk();
System.out.println(why.a); // 10
}
}

最佳答案

来自 docs :

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

上面的说法有点误导,因为如果我们按照上面文档的解释,我们可以像这样重写原来的代码:

public class WrongVersionOfWhyIsThisOk {

int a = 10;

public WhyIsThisOk (){
a = 5;
}

public static void main(String[] args){
WrongVersionOfWhyIsThisOk why = new WrongVersionOfWhyIsThisOk ();
System.out.println(why.a);
}
}

但是运行 WrongVersionOfWhyIsThisOk 将产生 5 个而不是原始代码产生的 10 个。

但实际上是初始化 block 和变量赋值都被复制到构造函数中:

public class RightVersionOfWhyIsThisOk {

int a;

public RightVersionOfWhyIsThisOk (){
a = 5;
a = 10;
}

public static void main(String[] args){
RightVersionOfWhyIsThisOk why = new RightVersionOfWhyIsThisOk ();
System.out.println(why.a);
}
}

更新:

这是 doc详细描述初始化顺序和构造函数调用:

4) Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5.

5) Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.

关于java - 为什么我的实例初始化程序 block 可以在声明之前引用一个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48215842/

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