Java 中所有類隱含繼承 java.lang.Object。掌握其 11 個方法(含 wait/notify 族群)是理解物件行為的基石。
| 方法 | 預設行為 | 覆寫契約/最佳實踐 |
|---|---|---|
toString() | 類名@雜湊碼 (如 User@15db9742) | 回傳「物件有意義的文字描述」,建議格式:ClassName[field=value, ...] |
equals(Object) | 參考比較 (this == obj) | 自反性、對稱性、傳遞性、一致性、非空性。覆寫 equals 必須覆寫 hashCode |
hashCode() | 記憶體地址衍生 (Native) | 相等物件必有相同 hashCode;不變性;盡量分佈均勻。常用 Objects.hash(fields...) |
clone() | 拋 CloneNotSupportedException | 實作 Cloneable、覆寫為 public、決定淺/深拷貝、考慮可變欄位防禦性複製 |
finalize() | 無操作 | 已棄用 (JDK 9),不可靠、效能差。改用 try-with-resources、Cleaner、PhantomReference |
getClass():回傳執行時類物件 Class<?>。wait()/notify()/notifyAll():監視器鎖協作,必須在 synchronized 區塊內呼叫。import java.util.Objects;
public final class Employee {
private final String id;
private final String name;
private final int age;
public Employee(String id, String name, int age) {
this.id = Objects.requireNonNull(id);
this.name = Objects.requireNonNull(name);
this.age = age;
}
// Getter 略
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee that = (Employee) o;
return age == that.age && id.equals(that.id) && name.equals(that.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name, age);
}
@Override
public String toString() {
return "Employee{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
public boolean equals(Employee e) → 這是**多載**而非覆寫,集合查找失效。HashMap/HashSet 行為異常。record Employee(String id, String name, int age) {} 自動產生正確的 equals/hashCode/toString/建構子/存取子,且不可變。@Data / @Value / @EqualsAndHashCode 編譯期生成。Objects 工具類。Object 方法定義了物件的身份、相等性、文字表現與生命週期協議。深刻理解 equals/hashCode 契約與 toString 診斷價值,是寫出正確集合操作、除錯友善、可維護代碼的前提。現代開發優先使用 record 或工具生成,避免手寫錯誤。