Java 中的非法自引用是什么?
What is Illegal Self Reference in Java?
当我尝试编译以下内容时 class
class C1 {
Integer v1 = v1;
}
我收到 Illegal Self Reference
错误。现在考虑另一个 class 如下。
class C2 {
Integer v1;
{
v1 = v1;
}
}
并编译。 classes 之间有什么区别,为什么一个可以编译而一个不能。
更新:
如果 v1
在 class C1
中不可用,那么为什么下面的 class 也有效?
class C3 {
Integer v1 = v1 = 1;
}
在上面 C3
class v1
可用于要计算的表达式 v1 = 1
但它在 C1
中的作用不同.你能解释一下吗?
v1
在你定义它之后开始存在,所以当你试图将值保存到它自己时它还不存在:
class C1 {
Integer v1 = v1;
//declaring-^ ^-doesn't exist yet
}
这是等效代码:
public class SomeClass {
Integer v1;
//声明....^
public SomeClass() {
this.v1 = v1;
// ^-----^
// |
// both exist
}
}
在你的例子中,实例块代码在声明变量之后执行,就像构造函数一样:
class C2 {
Integer v1;
{
v1 = v1; // instance block executed after variable declaration
}
}
更新问题的最后一部分在这里得到了很好的解释 https://softwareengineering.stackexchange.com/questions/205079/what-is-the-difference-advantage-of-doing-double-assignment
并在用户@user207421的评论中回答(关于正确关联)
当我尝试编译以下内容时 class
class C1 {
Integer v1 = v1;
}
我收到 Illegal Self Reference
错误。现在考虑另一个 class 如下。
class C2 {
Integer v1;
{
v1 = v1;
}
}
并编译。 classes 之间有什么区别,为什么一个可以编译而一个不能。
更新:
如果 v1
在 class C1
中不可用,那么为什么下面的 class 也有效?
class C3 {
Integer v1 = v1 = 1;
}
在上面 C3
class v1
可用于要计算的表达式 v1 = 1
但它在 C1
中的作用不同.你能解释一下吗?
v1
在你定义它之后开始存在,所以当你试图将值保存到它自己时它还不存在:
class C1 {
Integer v1 = v1;
//declaring-^ ^-doesn't exist yet
}
这是等效代码:
public class SomeClass {
Integer v1;
//声明....^
public SomeClass() {
this.v1 = v1;
// ^-----^
// |
// both exist
}
}
在你的例子中,实例块代码在声明变量之后执行,就像构造函数一样:
class C2 {
Integer v1;
{
v1 = v1; // instance block executed after variable declaration
}
}
更新问题的最后一部分在这里得到了很好的解释 https://softwareengineering.stackexchange.com/questions/205079/what-is-the-difference-advantage-of-doing-double-assignment
并在用户@user207421的评论中回答(关于正确关联)