[英]trying to reassign value to class instance variables
我是初学者,尝试学习Java基础知识,在此程序中,我很困惑为什么我们不能重新分配类实例变量的值。 这是该程序中的错误。 请大家帮我弄清楚。 谢谢
class AddInsideClassVar{
int a = 3;
int c;
c = a + a;
public static void main(String args[]){
System.out.println();
}
}
您可以在一个类中定义字段,但不允许将计算语句放在方法定义之外。 字段声明的格式类型为; 或类型=值;
例如(从您的代码);
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);
}
}
您不能在该部分执行c = a + a。 如果您需要做任何事情
int a = 3;
int c = a + a;
如果将这些变量设为静态,则可以
private static int a = 3;
private static int c;
static {
c = a + a;
}
您可以尝试以下方法(只是变通方法的一个示例):
class AddInsideClassVar{
static {
int a = 3;
int c;
c = a + a;
System.out.println(c);
}
public static void main(String args[]){
}
}
说明:int c = a + a是一个声明,而“ c = a + a;”(单独)是一个声明; 你有一点,这没有多大意义;
class MyClass {
int a = 3;
int c = a + a; // Correct
}
要么
class MyClass {
int a = 3;
int c;
public void addition () {
c = a + a; // Correct
}
}
但不是
class MyClass {
int a = 3;
int c;
c = a + a; // Incorrect
}
注意 :另一方面,Scala编程语言(编译为JVM)使您可以执行以下操作:
scala> class MyClass { val a:Int = 3;
var c:Int = _;
c = a + a ; // Correct
}
defined class MyClass
您可能将静态变量与实例变量混合在一起。 为了避免混淆自己,我将这样写:
public class AddInsideClassVar{
int a;
int c;
public void doStuff() {
a = 3;
c = a + a;
}
public static void main(String args[]){
AddInsideClassVar instance = new AddInsideClassVar();
instance.doStuff();
System.out.println(c);
}
}
a和c是实例变量。 它们是由非静态方法操纵的,该方法需要对该类的实例进行操作。 因此,我在main()中创建实例,然后调用该函数来操纵实例变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.