gpt4 book ai didi

java - 为什么静态字段自赋值只能使用显式静态语法进行编译?

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

为什么这段代码在右侧使用显式静态字段符号进行编译,但不是没有?

public class A
{
static int a = ++A.a; // compiles
//static int a = ++a; // error - cannot reference a field before it is defined

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

最佳答案

这就是语言规范的编写方式。具体来说,Sec 8.3.3说:

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 a class variable f declared in class or interface C, it is a compile-time error if:

  • ...

强调我的。

A.a 不是简单名称,因此不是编译时错误。

关于java - 为什么静态字段自赋值只能使用显式静态语法进行编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48157821/

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