← 中文资源

简体中文版本

record 的重载构造器

record 的附加构造器必须通过 this(...) 委托给规范构造器:按晚数推导退房日、从 ISO 字符串解析入住日,三条构造路径殊途同归,组件访问器不受影响。

阅读英文原文

实现说明

真正干活的是类 EventWindows、Reservation和函数 Reservation、main,其余都是接线。

使用要点

  • 直接运行文件,输出会带上标签,比如 same checkout:、accessors intact:——输出的每一行都能指回产生它的那次调用。
  • 执行文件,main 会按顺序走完 Reservation。

常见问题

运行「record 的重载构造器」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 same checkout:、accessors intact: 这类标签。

主要签名是 public record Reservation(String guest, LocalDate checkIn, LocalDate checkOut)

核心语句

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);

代码示例

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());
    }
}