record trong Java là gì? Khi nào nên dùng record thay vì class thường?
record trong Java là gì? Khi nào nên dùng record thay vì class thường?
Record (chính thức từ Java 16) là class mang dữ liệu bất biến, compiler tự sinh: constructor, accessor, equals, hashCode, toString.
public record Money(BigDecimal amount, String currency) {
public Money { // compact constructor để validate
Objects.requireNonNull(currency);
if (amount.signum() < 0) throw new IllegalArgumentException("Số tiền âm");
}
public Money add(Money other) { // vẫn có method
return new Money(amount.add(other.amount), currency);
}
}
var price = new Money(new BigDecimal("150000"), "VND");
price.amount(); // accessor tên là amount(), không phải getAmount()
price.equals(new Money(new BigDecimal("150000"), "VND")); // true
private final; record là final, không kế thừa class khác (ngầm kế thừa java.lang.Record), nhưng implement interface được.Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.