gpt4 book ai didi

java - 为什么此代码有效?先赋值再声明?

转载 作者:搜寻专家 更新时间:2023-11-01 01:05:07 24 4
gpt4 key购买 nike

这是Java。我知道将 1 分配给 index 是在实例化类时首次运行的 initialization block 中,但为什么这是有效的?

public class arr {
{
index = 1;
}

int index;

void go() {
System.out.println(++index);
}
public static void main(String [] args){
new arr().go();
}
}

输出为 2。

我应该得到一个 symbol not found 编译错误。这种行为是初始化 block 固有的吗?在正常场景中,int index; 应该在 index = 1; 之前。

最佳答案

+1,看起来真的很奇怪。但事实上,非静态初始化 block 只是由 javac 插入到对象构造函数中。如果我们反编译 arr.class,我们将得到真正的代码

public class arr {
int index;

public arr() {
index = 1;
}

void go() {
System.out.println(++index);
}

public static void main(String args[]) {
(new arr()).go();
}

}

让这个谜题变得更有趣

public class A {
int index;

A() {
index = 2;
}

{
index = 1;
}
}

什么是新的 A().index ?正确答案是2。看反编译的A.class

class A {
int index;

A() {
index = 1;
index = 2;
}
}

也就是说,非静态初始化 block 首先出现在对象构造函数中

关于java - 为什么此代码有效?先赋值再声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14089974/

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