Given:
public class TestField {
int x;
int y;
public void doStuff(int x, int y) {
this.x = x;
y = this.y;
}
public void display() {
System.out.print(x + " " + y + " : ");
}
public static void main(String[] args) {
TestField m1 = new TestField();
m1.x = 100;
m1.y = 200;
TestField m2 = new TestField();
m2.doStuff(m1.x, m1.y);
m1.display();
m2.display();
}
}
What is the result?
A.
100 200 : 100 200 :
B.
100 0 : 100 0 :
C.
100 200 : 100 0 :
D.
100 0 : 100 200 :
题解
先看到程序第 8 行,「doStuff」方法内并没有将参数 y 的值指派给对象的 y 变量,因此「doStuff」方法只会更动对象的 x 变量。
第 17~18 行,直接去设置 m1 对象的 x 和 y 这两个对象变量。设置完成后 m1.x 为 100, m1.y 为 200。
第 20 行使用 m2 对象的「doStuff」方法只会更动到对象变量 x,所以设置完成后 m2.x 为 100, m2.y 为 0。
因此选项 C 是正确的。
