代碼中 class A 的方法 f() 創建新實例 a 並訪問 a.i、a.s(均為 private),編譯通過且運行正常。這揭示了Java private 的真實含義:
private 修飾的成員,對同一頂層類內部的所有代碼可見,與實例無關。
class A 內部(包括靜態方法、實例方法、構造器、內部類)均可直接讀寫 A 的任何 private 字段/方法,無論是 this 還是其他 A 實例。private(類級可見)一致,不同于「實例私有」(如Ruby private 方法只能隱式調用)。便於實現「拷貝構造」、「工廠方法」、「比較器」等需要訪問同類其他實例內部狀態的場景,無需暴露公共Getter/Setter破壞封裝。
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof A)) return false;
A other = (A) o;
return this.i == other.i && this.s.equals(other.s); // 直接訪問 other 私有字段
}