Chapter 3 of 12
Course Progress0 of 12 completed (0%)

Java & Spring Boot Enterprise Mastery · Chapter 3 · ~15 min · Intermediate

Clean OOP, Sealed Classes & Modern Java Records

Transform bloated legacy Java object models into clean, modern, and type-safe domain architectures. Master immutable Java 21 records, sealed class hierarchies with explicit permits, and exhaustive pattern matching switch expressions.

  • Design clean domain models using polymorphism and interface contracts
  • Replace verbose JavaBean boilerplate with immutable Java 21 records
  • Enforce closed class hierarchies using sealed classes and permits
  • Leverage pattern matching in switch expressions for exhaustive type handling

Clean OOP, Sealed Classes & Modern Java Records: learn it visually

Transform bloated legacy Java object models into clean, modern, and type-safe domain architectures. Master immutable Java 21 records, sealed class hierarchies with explicit permits, and exhaustive pattern matching switch expressions.

Clean OOP, Sealed Classes & Modern Java RecordsTransform bloated legacy Java object models into clean, modern, and type-safe domain architectures. Master immutable Java 21 records, sealed class hierarchies with explicit permits, and exhaustive pattern matching switch expressions.UNDERSTANDSeal class choicesFOLLOW THE FLOWCALLCreate Java recordsAPPLY ITCompose objectsClean OOP, Sealed Classes & Modern Java RecordsTransform bloated legacy Java object models into clean, modern, and type-safe domain architectures. Master immutable Java 21 records, sealed class hierarchies with explicit permits, and exhaustive pattern matching switch expressions.UNDERSTANDSeal class choicesFOLLOW THE FLOWCALLCreate Java recordsAPPLY ITCompose objects

1The Death of JavaBean Boilerplate: Modern Java Records

For over two decades, enterprise Java developers spent billions of hours writing and maintaining JavaBean POJOs (Plain Old Java Objects). Every simple data container required:

  • Private fields with verbose public getter and setter methods
  • A repetitive multi-parameter constructor duplicating parameter assignments
  • Handwritten or Lombok-generated equals(), hashCode(), and toString() methods
  • Accidental mutability traps where one thread mutates an order status while another thread reads it
Legacy Java 8 (50+ Lines)

Mutable Customer POJO

Mutable fields, getters, setters, synchronized blocks, fragile equals() and hashCode() implementations susceptible to field addition bugs.

Modern Java 21 (1 Line)

Immutable Record

record Customer(UUID id, String email, Instant created) {}. Immutable, thread-safe, auto-generated canonical constructor, accessors, equals, and hash code.

// Java 21 Immutable Record with Compact Constructor Validation
public record CreateAccountRequest(
    UUID customerId,
    String email,
    BigDecimal initialDeposit
) {
    // Compact constructor: runs before field assignment without duplicating "this.x = x"
    public CreateAccountRequest {
        Objects.requireNonNull(customerId, "customerId must not be null");
        if (email == null || !email.contains("@")) {
            throw new IllegalArgumentException("Invalid email format: " + email);
        }
        if (initialDeposit.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("Initial deposit cannot be negative");
        }
    }
}
Concept Check

What happens when you declare a Java record, such as 'record User(String name, int age) {}'?

2Dual Mental Model: POJO Boilerplate vs Sealed Records

Compare the cognitive shift between legacy mutable POJO patterns and modern closed algebraic domain types in Java 21:

Wrong idea: Mutable JavaBean POJOs with 60 lines of getters & setters

class Order { private String id; void setId(String id) {...} }Accidental mutation · null hazards · verbose boilerplate

Writing endless boilerplate with mutable setters, boilerplate equals(), hashCode(), and toString() methods where fields can be mutated unexpectedly.

Real system: Immutable Java 21 Records with automatic canonical constructor

public record Order(String id, double total) {}1-line immutable data carrier · thread-safe · zero boilerplate

Declaring compact immutable data carriers with record Order(String id, double total) where all fields are private final and methods are compiler-synthesized.

3Sealed Classes & Permits: Closing the Inheritance Hierarchy

In standard Object-Oriented Programming, any class marked public can be extended by any other class anywhere in the application classpath. This open inheritance model makes exhaustive domain modeling impossible.

Sealed Classes and Interfaces (sealed) let you restrict which classes or interfaces may extend or implement them using the permits keyword:

// Define an exhaustive domain model for bank loan applications
public sealed interface LoanApplication
    permits MortageLoan, AutoLoan, PersonalLoan {
    
    UUID applicationId();
    BigDecimal requestedAmount();
}

public record MortageLoan(
    UUID applicationId,
    BigDecimal requestedAmount,
    String propertyAddress,
    BigDecimal downPayment
) implements LoanApplication {}

public record AutoLoan(
    UUID applicationId,
    BigDecimal requestedAmount,
    String vinNumber
) implements LoanApplication {}

public record PersonalLoan(
    UUID applicationId,
    BigDecimal requestedAmount,
    int creditScore
) implements LoanApplication {}
Concept Check

Why does a sealed interface with permits enable exhaustive pattern matching without a default branch?

4Interactive Visualizer: Sealed Hierarchy & Pattern Matcher

Test how modern Java 21 evaluates polymorphic events using sealed hierarchies and pattern matching. Select different payment events to witness record deconstruction and compiler exhaustiveness:

Sealed Hierarchy & Pattern Matching Inspector

Test how Java 21 sealed types and pattern matching deconstruct immutable records with compiler exhaustiveness

Select a Polymorphic Domain Event:

1. Domain Interface Contract
Java 21 Sealed Model
public sealed interface PaymentEvent
permits CardPayment, CryptoPayment, BankTransfer {
double amount();
}

The permits clause closes the hierarchy. The compiler knows exactly every valid subtype that can ever implement this interface.

2. Switch Expression Deconstruction
COMPILER VERIFIED
// Input Instance:
new CardPayment("4111-XXXX-9921", 249.99, "STRIPE")
// Pattern Match Hit:
case CardPayment(var card, var amt, var provider) ->
Execution Result:Card Approved: 4111-XXXX-9921 via STRIPE ($249.99)
Why Exhaustiveness Matters: Because the hierarchy is sealed to exactly 3 permits, the switch expression does not require a default: branch! If a new permit is added tomorrow, javac will immediately fail the build across every switch in your company codebase that forgets to handle it.

5Pattern Matching in Switch Expressions

Prior to Java 21, handling polymorphic types required cascading if (obj instanceof Subclass) blocks with manual type casts. Modern Java switch expressions provide pattern matching with record deconstruction and guarded patterns (when clause):

public class LoanUnderwritingEngine {

    public static BigDecimal calculateRiskScore(LoanApplication loan) {
        // Exhaustive switch expression with record pattern matching & guards
        return switch (loan) {
            case MortageLoan(var id, var amt, var addr, var down) when down.doubleValue() >= 0.20 * amt.doubleValue() ->
                BigDecimal.valueOf(1.5); // Low risk: 20%+ down payment
                
            case MortageLoan m ->
                BigDecimal.valueOf(3.8); // Standard mortgage
                
            case AutoLoan(var id, var amt, var vin) ->
                BigDecimal.valueOf(2.5);
                
            case PersonalLoan(var id, var amt, var score) when score > 750 ->
                BigDecimal.valueOf(2.0); // Excellent credit personal loan
                
            case PersonalLoan p ->
                BigDecimal.valueOf(5.0); // High risk personal loan
        };
        // Zero 'default' branch needed! The compiler guarantees total coverage.
    }
}

6Code Bug Hunt: Unsealed Subclass & Pattern Match

Inspect the starter code below. The legacy payment processor uses unsealed interfaces, mutable classes with manual getters, and old-fashioned instanceof casting. Modernize it to use a sealed interface with permits, an immutable record, and pattern matching:

Modernize Payment Event with Sealed Records
Java

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?

Modernize the hierarchy with Java 21 features:

  • Declare public sealed interface PaymentEvent permits CardPayment with double getAmount();.
  • Replace the verbose JavaBean class with an immutable record: public record CardPayment(String cardNumber, double amount) implements PaymentEvent {}.
  • Replace the if (event instanceof CardPayment) block with pattern matching in a switch expression: return switch (event) { case CardPayment cp -> ... };.

7Chapter Knowledge Challenge

Verify your mastery of clean object-oriented architecture and Java 21 features before proceeding:

Concept Check 1 of 2
1

Can a Java record extend another class, such as 'public record Employee(...) extends Person'?

Concept Check 2 of 2
2

What modifier must a non-record permitted subclass of a sealed class declare?

8Recap

  • Java Records replace dozens of lines of JavaBean boilerplate with compact, immutable, thread-safe data carriers with compiler-generated accessors, equals, and hashCode.
  • Compact constructors in records allow immediate validation of invariants without repeating field assignment statements.
  • Sealed classes and interfaces (sealed ... permits) create closed algebraic data types that restrict inheritance to known, trusted subtypes.
  • Pattern matching in switch expressions eliminates unsafe manual casting and provides compiler-enforced exhaustiveness checks without requiring a default branch.

Ready for Chapter 4? Mark this chapter as complete to proceed:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us