Records, Sealed Classes and Pattern Matching
Modern Java (17 to 25) added records for data carriers, sealed classes to restrict hierarchies, and pattern matching in instanceof and switch. Interviewers increasingly ask about them because they change how DTOs and domain models are written.
What you will learn
- Write records with compact constructors for validation
- Restrict hierarchies with sealed and permits
- Use switch pattern matching with record patterns
- Know text blocks and var
Key concepts
Record
A final, immutable data class: fields, constructor, accessors, equals, hashCode and toString generated from its components. Great for DTOs and value objects. Not for JPA entities, which need mutability and a no-arg constructor.
Sealed class
sealed interface Shape permits Circle, Square lists every allowed subtype, so the compiler knows the hierarchy is closed.
Pattern matching
if (obj instanceof String s) binds s directly. switch can match types and deconstruct records, and with a sealed type the compiler checks the switch covers every case.
Step by step
Records with validation
public record Money(BigDecimal amount, String currency) {
public Money { // compact constructor
Objects.requireNonNull(amount);
if (amount.signum() < 0) throw new IllegalArgumentException("negative amount");
currency = currency.toUpperCase();
}
public Money plus(Money o) { return new Money(amount.add(o.amount), currency); }
}Examples
Sealed types with an exhaustive switch
public sealed interface PaymentResult permits Success, Declined, Pending {}
public record Success(String txnId) implements PaymentResult {}
public record Declined(String reason) implements PaymentResult {}
public record Pending(Duration retryAfter) implements PaymentResult {}
String message = switch (result) {
case Success(String txnId) -> "Paid, ref " + txnId;
case Declined(String reason) -> "Declined: " + reason;
case Pending p when p.retryAfter().toMinutes() > 5 -> "Taking longer than usual";
case Pending p -> "Processing";
}; // no default needed: the compiler knows every casePractise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Convert a Lombok @Value DTO to a record.
- Model an order state machine with a sealed interface and handle it with a switch.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
Can a record extend a class?
No. A record implicitly extends java.lang.Record and is final. It can implement interfaces, have static fields, static and instance methods, and nested types.
Why are records not good JPA entities?
JPA providers need a no-arg constructor, mutable state for dirty checking and proxies for lazy loading, and records are final and immutable. Use records for DTOs and projections instead.
Summary
Records are concise immutable data carriers, sealed types close a hierarchy, and pattern matching in switch with record patterns gives exhaustive, readable branching.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus