Given:
public class Access {
private int x = 0;
private int y = 0;
public static void main(String[] args) {
Access accApp = new Access();
accApp.printThis(1, 2);
accApp.printThat(3, 4);
}
public void printThis(int x, int y) {
x = x;
y = y;
System.out.println("x:" + this.x + " y:" + this.y);
}
public void printThat(int x, int y) {
this.x = x;
this.y = y;
System.out.println("x:" + this.x + " y:" + this.y);
}
}
What is the result?
A.
x:1 y:2
x:3 y:4
x:3 y:4
B.
x:0 y:0
x:3 y:4
x:3 y:4
C.
x:1 y:2
x:0 y:0
x:0 y:0
D.
x:0 y:0
x:0 y:0
x:0 y:0
題解
第 13、14 行,printThis 方法的 x、y 參數會遮蔽 Access 類別的 x、y 物件欄位,所以 Access 物件欄位的值並不會被修改到,維持原來的 x=0、y=0。
第 19、20 行,printThat 方法的 x、y 參數會遮蔽 Access 類別的 x、y 物件欄位,但在這裡使用了「this」來表示目前 Access 物件的參考,所以可以存取到 Access 物件欄位,欄位的值會成功被修改,變成 x=3、y=4。
