gpt4 book ai didi

java - 为什么我可以分配给在初始化程序之后声明的变量,但不能打印它?

转载 作者:行者123 更新时间:2023-12-04 01:05:55 25 4
gpt4 key购买 nike

我对初始化顺序感到困惑,无法解释为什么编译第 7 行 b = 3; 但下一行 8 System.out.println("b: "+ b ); 不是。有人可以对此进行解释并填补这一知识空白吗?

没有第 8 行,代码可以很好地编译并打印“2 4”。

public class InitializationOrder {

Integer a = 1;

{
a = 2;
b = 3;
System.out.println("b: " + b); // DOES NOT COMPILE
// InitializationOrder.java:8: error: illegal forward reference
// System.out.println("b: " + b);
// ^
// 1 error
// error: compilation failed
}

Integer b = 4;

public InitializationOrder() {
System.out.println(a + " " + b); // 2 4 - when line 8 is commented
}

public static void main(String[] args) {
InitializationOrder obj = new InitializationOrder();
}
}

最佳答案

这是 Java Language Specification 记录的初始化器中字段引用限制的一部分:

References to a field are sometimes restricted, even through the field is in scope. The following rules constrain forward references to a field (where the use textually precedes the field declaration) as well as self-reference (where the field is used in its own initializer).

...

For a reference by simple name to an instance variable f declared in class C, it is a compile-time error if:

  • The reference appears either in an instance variable initializer of C or in an instance initializer of C (§8.6); and
  • The reference appears in the initializer of f's own declarator or at a point to the left of f's declarator; and
  • The reference is not on the left hand side of an assignment expression (§15.26); and
  • The innermost class enclosing the reference is C.

JLS 描述了为什么要应用这些限制:

The restrictions above are designed to catch, at compile time, circular or otherwise malformed initializations.

所以基本上是为了避免这样的情况:

class Test {
int i = j;
int j = i;
}

(即使在您的情况下打印字段可能不是一件危险的事情)

关于java - 为什么我可以分配给在初始化程序之后声明的变量,但不能打印它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66489940/

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