Records, enums and sealed types
Enums (Java 5) represent a fixed set of constants and can have fields, constructors and methods.
Records (final in Java 16) are transparent, immutable data carriers. One line gives you a constructor, accessor methods, equals(), hashCode() and toString(). They're ideal for DTOs, API responses and value objects.
Sealed classes and interfaces (final in Java 17) list exactly which types may extend them with permits. Each permitted subclass must be final, sealed or non-sealed.
Together, records and sealed interfaces model data precisely, and since Java 21 the compiler can check that a switch handles every case.
Example
enum Plan {
FREE(0), PRO(499);
final int priceInr;
Plan(int price) { this.priceInr = price; }
}
record CourseDto(String title, int lessons, Plan plan) {
CourseDto { // compact constructor
if (lessons <= 0) throw new IllegalArgumentException("lessons must be positive");
}
}
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
double area(Shape s) {
return switch (s) { // exhaustive: no default needed
case Circle c -> Math.PI * c.r() * c.r();
case Square q -> q.side() * q.side();
};
}Common mistake
Trying to use a record as a JPA @Entity. Use records for DTOs and projections instead.
Under the hood
Records are final, their fields are private final, and they can't extend other classes (they implicitly extend java.lang.Record). They're only shallowly immutable: a List component can still be changed, so copy it with List.copyOf in the compact constructor. Jackson and Spring MVC bind records out of the box. JPA entities can't be records (entities need a no-arg constructor and mutable state), but records work well as query projections and, since Jakarta Persistence 3.2, as embeddables.
Check yourself
How do you read the title of record CourseDto(String title, ...)?
How this connects
Know these first
Part of Java from zero, Upgrade from Java 8 to Java 25.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.