我是初学者,尝试学习java基础知识,在这个程序中,我很困惑为什么我们不能重新分配类实例变量的值。

这是程序中的错误。拜托伙计们帮我弄清楚。谢谢
class AddInsideClassVar{
int a = 3;
int c;
c = a + a;
public static void main(String args[]){
System.out.println();
}
}发布于 2014-02-27 20:23:19
您可以在类中定义字段,但不允许将计算语句置于方法定义之外。字段声明是形式类型的;或类型=值;
例如(从您的代码);
class AddInsideClassVar{
static int a = 3; // ok this is a declaration for a field (variable)
static int c; // ok, this is too
//c = a + a; // this is a statement and not a declaration. A field may be
// declared only once
static int d = a + a; // this will work since it is part of a declaration.
public static void main(String args[]){
System.out.println("a=" + a + ", c=" + c + ", d=" + d);
}
}发布于 2014-02-27 20:01:30
您不能在该节中执行c=a+a。如果你需要做什么
int a = 3;
int c = a + a; 如果使这些变量是静态的,那么可以这样做。
private static int a = 3;
private static int c;
static {
c = a + a;
}发布于 2014-02-27 20:02:34
您可以尝试这样做(只是解决办法的一个例子):
class AddInsideClassVar{
static {
int a = 3;
int c;
c = a + a;
System.out.println(c);
}
public static void main(String args[]){
}
}https://stackoverflow.com/questions/22079046
复制相似问题