最近,我觀察到訪問Java中priavte字段的意外行爲。請看下面的例子,它說明了行爲:爲什麼允許訪問另一個對象的私有字段?
public class A {
private int i; <-- private field!
public A(int i) {
this.i = i;
}
public void foo(A a) {
System.out.println(this.i); // 1. Accessing the own private field: good
System.out.println(a.i); // 2. Accessing private field of another object!
}
public static void main(String[] args) {
(new A(5)).foo(new A(2));
}
}
爲什麼允許我在foo
方法(第二種情況)內訪問A
類的其他對象的私有字段?
請使用代碼格式設置代碼,輸入/輸出和結構化文檔,如HTML或XML。爲此,請選擇樣本並單擊郵件發佈/編輯表單上方的「{}」按鈕。 –