private int field;
public void f(int n) {
n = n + field;
field = field + n;
n = n + 2;
}
public void g() {
field = 2;
f(field);
}
调用g()
后字段的最终值是多少?我知道答案是6但是有人可以解释一下原因吗?
答案 0 :(得分:7)
您可以将代码扩展为以下内容:
field = 2; // field == 2
int n = field; // n == 2; field == 2
n = n + field; // n = 2+2 == 4; field == 2
field = field + n; // n == 4; field = 2+4 == 6
n = n + 2; // n = 4+2 == 6; field == 6
最终价值观:
field == 6
n == 6
注意:a = b
表示只有b
存储/复制到a
的值,但a
和b
是两个不相关的变量彼此
答案 1 :(得分:1)
然后计算(包含在方法 f 中)是明确的:
n = n + field; // n = 2 + 2 == 4
field = field + n; // field = 2 + 4
n = n + 2; // n = 4 + 2 == 6