给出以下代码:
public class Test1 {
int i;
i = 4;
}
public class Test2 {
public static void main(String[] args) {
Test1 t1 = new Test1();
System.out.println(t1.i);
}
}
为什么当我尝试编译 Test2 时会得到以下信息?
./Test1.java:3: error: <identifier> expected
i = 4;
^
./Test1.java:3: error: cannot find symbol
i = 4;
^
symbol: class i
location: class Test1
2 errors
最佳答案
您不能在类主体中分配变量。试试这个:
public class Test1 {
int i;
{
i = 4;
}
}
作为替代方案,您可以在构造函数或 setter 方法中分配 i
:
public class Test1 {
int i;
public Test1(int i) {
this.i = i;
}
public void setI(int i) {
this.i = i;
}
}
关于java - 需要标识符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29887714/