JAVA · 기초 문법
Record 클래스 (Java 16+)
불변 데이터 클래스를 위한 Record. equals, hashCode, toString, getter를 자동 생성합니다.
기초 문법중급RecordJava 16compact constructorimmutableDTO
핵심 설명
불변 데이터 클래스를 위한 Record. equals, hashCode, toString, getter를 자동 생성합니다.
Java code
import java.util.Objects;
// Record — 불변 데이터 클래스
public record Point(double x, double y) {
// compact constructor — 유효성 검사
public Point {
if (Double.isNaN(x) || Double.isNaN(y)) {
throw new IllegalArgumentException("NaN 불가");
}
}
// 추가 메서드
public double distance() {
return Math.sqrt(x * x + y * y);
}
public Point translate(double dx, double dy) {
return new Point(x + dx, y + dy); // 새 Record 반환
}
}
// Generic Record
public record Pair<A, B>(A first, B second) {
public static <A, B> Pair<A, B> of(A a, B b) {
return new Pair<>(a, b);
}
}
// Record implements interface
public interface Shape {
double area();
}
public record Circle(double radius) implements Shape {
@Override
public double area() {
return Math.PI * radius * radius;
}
}
class Main {
public static void main(String[] args) {
var p1 = new Point(3, 4);
var p2 = new Point(3, 4);
System.out.println(p1.x()); // 3.0 (accessor)
System.out.println(p1.distance()); // 5.0
System.out.println(p1.equals(p2)); // true
System.out.println(p1); // Point[x=3.0, y=4.0]
var translated = p1.translate(1, 2);
System.out.println(translated);
var pair = Pair.of("Java", 21);
System.out.println(pair.first() + " " + pair.second());
}
}학습 팁
Record는 상속이 불가능합니다(암묵적으로 final). 인터페이스 구현은 가능합니다. 불변 DTO, Value Object 패턴에 완벽합니다.
주의할 점
Record의 접근자 메서드는 getX()가 아닌 x()입니다. 기존 JavaBeans 컨벤션과 다르므로 Jackson 같은 라이브러리 설정 시 주의하세요.
자주 묻는 질문
Record 클래스 (Java 16+)란 무엇인가요?
불변 데이터 클래스를 위한 Record. equals, hashCode, toString, getter를 자동 생성합니다.
Record 클래스 (Java 16+) 학습 시 주의할 점은 무엇인가요?
Record의 접근자 메서드는 getX() 가 아닌 x() 입니다. 기존 JavaBeans 컨벤션과 다르므로 Jackson 같은 라이브러리 설정 시 주의하세요.
Continue Learning
Java 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.