public final class Schedule {
private final Date start;
private final Date end;
public Schedule(Date start, Date end) {
if (start.compareTo(end) > 0)
throw new IllegalArgumentException(start + " after " + end);
this.start = start;
this.end = end;
}
public Date getStart() { return start; }
public Date getEnd() { return end; }
}
Schedule(Date, Date)Schedule() {} 後編譯報錯final 修飾的實例變量必須在構造器結束前完成初始化當手動添加 public Schedule() {} 時:
final 實例變量(start、end)variable start might not have been initializedpublic Schedule() {
this.start = new Date(); // 當前時間
this.end = new Date(); // 當前時間
// 或根據業務邏輯設置合理默認值
}
public Schedule() {
this(new Date(), new Date()); // 調用帶參構造器,復用驗證邏輯
}
若 Schedule 代表「有明確起止時間的日程」,則不應存在無參構造器。強制調用方提供參數,體現「始終處於有效狀態」的設計原則。
若使用 Jackson、Gson、Hibernate 等框架,它們可能需要無參構造器:
@JsonCreator 標註帶參構造器,或提供 private 無參構造器protected 或 public 無參構造器protected Schedule() {} 滿足框架要求,同時不暴露給業務代碼final 字段必須在所有構造器中初始化