在定义字段之前无法引用字段,但前提是您不符合条件 [英] Cannot reference a field before it is defined, but only if you don't qualify it
问题描述
我发现发生以下代码让我的下巴掉了下来:
I found happening with the following code made my jaw drop:
public class MCVE {
{ // instance initializer
System.out.println(test); // cannot reference a field before it is defined
System.out.println(this.test);
}
private final String test = "wat";
}
行 System.out.println(测试) ;
给出错误
在定义之前无法引用字段。
Cannot reference a field before it's defined.
但行 System.out.println(this.test);
不
推荐答案
与许多这些问题一样,这是因为 JLS这样说。
As with so many of these questions, it's because the JLS says so.
8.3.2.3初始化期间使用字段的限制
成员的声明只有在成员是实例(分别为
static
)字段时才需要以文本方式显示类或接口C的所有条件和以下所有条件:
8.3.2.3 Restrictions on the use of Fields during Initialization
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:
- 使用情况发生s在C的实例(分别是
static
)变量初始化程序中或在C的实例(分别为static
)初始化程序中。 - 使用情况不在作业的左侧。
- 使用方法是通过一个简单的名称。
- C是封闭用法的最内层类或接口。
- The usage occurs in an instance (respectively
static
) variable initializer of C or in an instance (respectivelystatic
) 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.
如果有的话,这是一个编译时错误不符合上述四项要求。
在您的(失败)示例中,简单名称案例是条件没有达到。限定使用(使用此
)是解决编译时错误的漏洞。
In your (failing) example, the "simple name" case is the condition not met. Qualifying the usage (with this
) is the loophole that resolves the compile-time error.
字段的使用在声明它们的行之前的初始化块内部只能位于表达式的左侧(即赋值),除非它们是合格的(在您的情况下
this.test
)。
(更详细地解释为适合这个问题)
(paraphrased to suit this question more closely)
这篇关于在定义字段之前无法引用字段,但前提是您不符合条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!