正如预期的那样,这无法编译(出现 illegal forward reference
错误):
class test {
int x = x + 42;
}
但这有效:
class test {
int x = this.x + 42;
}
发生了什么事?在后一种情况下分配了什么?
最佳答案
在 x 的初始化过程中发现和禁止对 x
的所有访问太难了。例如
int x = that().x; | int x = getX();
|
Test that(){ return this; } | int getX(){ return x; }
规范停留在“通过简单名称访问”,并没有尝试更全面。
在另一部分“明确分配”中,规范做了类似的事情。例如
public class Test
{
static final int y;
static final int z = y; // fail, y is not definitely assigned
static{ y = 1; }
}
public class Test
{
static final int y;
static final int z = Test.y; // pass... because it's not a simple name
static{ y = 1; }
}
有趣的是,“定义赋值”特别提到 this.x
等价于 x
(or, for a field, the simple name of the field qualified by this)
这个子句也可以添加到 NPE 引用的部分。
- the usage is via a simple name (or a simple name qualified by this)
但最后,不可能在编译时分析所有可能的使用/访问一个字段。
关于java - 当我添加 "this"时,递归初始化程序有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15820302/