【发布时间】:2014-04-01 19:49:07
【问题描述】:
有以下两个类:
class1
int a = 10;
public void Main(String[] args){
System.out.println(a); // will print "10"
class2 c2 = new class2();
class2.ChangeValue(a);
System.out.println(a); // will print "10" even after the value has
// been set to 20 in the other class
}
class2
public void ChangeValue(int a){
a = 20;
System.out.println(a) // will print "20"
}
问题是,如何让这个值在所有类中都为 20,而不仅仅是更改它的类。
【问题讨论】:
-
您在类 1 中打印 a 并在类 2 中更改 a。这两个 a 字段虽然名称相同,但区域完全不同。您可以将其设为静态。