【发布时间】:2019-12-04 09:30:02
【问题描述】:
我正在尝试编写一个代码,该代码递增一个声明为类变量的整数数组,分别使用该类的 2 个不同对象。
class Foo {
int n[];
Foo(int n1[], int x, int y) {
n = new int[]{0, 0, 0, 0};
n1[0] = n1[0] + x;
n1[1] = n1[1] + y;
this.n = n1;
}
}
public class stats {
public static void print(Foo obj) {
for (int i = 0; i < obj.n.length; i++) {
System.out.println(obj.n[i]);
}
}
public static void main(String[] args) {
int n[] = {1, 1, 1, 1};
Foo a = new Foo(n, 1, 1);
Foo b = new Foo(n, 2, 2);
print(a);
print(b);
}
}
预期输出:
2
2
1
1
3
3
1
1
实际输出
4
4
1
1
4
4
1
1
尽管没有将变量声明为静态变量,但是否有理由将对象中的数组递增为静态变量?就像每个整数数组都声明为类变量一样是静态的吗?我将如何获得预期的输出?
【问题讨论】:
-
this.n = n1;用参数n1的数组对象覆盖字段n。 -
您在
class Foo中声明的int n[];是实例变量,而不是类变量。类变量是用static关键字声明的变量。