Record Overloaded Constructors
Add secondary record constructors that delegate to the canonical one, deriving checkout dates and parsing ISO strings without breaking component accessors.
Code
import java.time.LocalDate;
public class EventWindows {
public record Reservation(String guest, LocalDate checkIn, LocalDate checkOut) {
// 附加构造器必须经 this(...) 委托到规范构造器,不能直接赋值组件
public Reservation(String guest, LocalDate checkIn, int nights) {
this(guest, checkIn, checkIn.plusDays(nights));
}
// 字符串入口:再包一层委托链,解析 ISO 日期后复用上面的 overload
public Reservation(String guest, String checkInIso, int nights) {
this(guest, LocalDate.parse(checkInIso), nights);
}
}
public static void main(String[] args) {
Reservation canonical = new Reservation("ada",
LocalDate.of(2026, 12, 1), LocalDate.of(2026, 12, 4));
Reservation byNights = new Reservation("lin", LocalDate.of(2026, 12, 1), 3);
Reservation fromIso = new Reservation("kim", "2026-12-05", 2);
System.out.println(canonical);
System.out.println(byNights);
System.out.println(fromIso);
// 三条构造路径殊途同归:组件值一致
System.out.println("same checkout: " + canonical.checkOut().equals(byNights.checkOut()));
System.out.println("accessors intact: " + fromIso.guest() + "@" + fromIso.checkIn());
}
}Order of operations
The working surface is the classes EventWindows and Reservation and the functions Reservation and main — everything else is wiring.
Caveats
- Every behavior here comes straight out of the standard library.
Putting it to use
Signature: public record Reservation(String guest, LocalDate checkIn, LocalDate checkOut)
The run prints same checkout:, accessors intact: — each prefix names the step that produced it.
Start the program and main runs Reservation one after another.
Core lines
Reservation byNights = new Reservation("lin", LocalDate.of(2026, 12, 1), 3);
Reservation fromIso = new Reservation("kim", "2026-12-05", 2);
this(guest, LocalDate.parse(checkInIso), nights);
Interactive Tools for This Topic
FAQ
- What does Record Overloaded Constructors print when run?
- Running the file directly is enough — expect labeled output lines such as `same checkout:`, `accessors intact:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.