gpt4 book ai didi

java - 我可以在声明前访问静态 block 中的静态字段吗?

转载 作者:行者123 更新时间:2023-11-29 10:02:46 25 4
gpt4 key购买 nike

我对下面的代码感到困惑,我预计它会给出一个错误或答案将是 10 但它给出了 20 怎么办?

public class test {
public static void main(String[] args) {
System.out.println(x);
}

static{
x=10;
}

static int x=20;
}

最佳答案

section 12.4.2 of the JLS 中指定,它给出了类初始化的细节:

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

变量初始值设定项 (x = 20) 在程序文本中出现在静态初始值设定项(包含 x = 10 的 block )之后。因此,初始化结束时的值为 20。

如果您调换轮次顺序,使变量初始值设定项排在第一位,您将看到 10。

不过,我强烈建议您尽可能避免编写依赖于文本排序的代码。

编辑:该变量仍然可以在静态初始值设定项中使用,因为它在范围内——就像您可以在先于变量声明的方法中使用实例变量一样。然而,section 8.3.2.3对此给出了一些限制:

The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:

  • The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.

  • The usage is not on the left hand side of an assignment.

  • The usage is via a simple name.

  • C is the innermost class or interface enclosing the usage.

It is a compile-time error if any of the four requirements above are not met.

因此,如果您将静态初始值设定项更改为:

static {
System.out.println(x);
}

然后你会得到一个错误。

但是,您现有的静态初始化器以符合所有限制的方式使用 x

关于java - 我可以在声明前访问静态 block 中的静态字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18889283/

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