On this page
  1. Classes, Records & Sealed Hierarchies
  2. Overview
  3. Choosing a Type Construct
  4. Compact Constructors & Invariant Validation
  5. Sealed Hierarchies & Exhaustive Pattern Matching
  6. Composition Over Inheritance

Classes, Records & Sealed Hierarchies

Prev: Language & OOP | Up: Language & OOP | Next: Generics & Type Erasure
Rel: record, sealed, interface, enum, switch expressions, Modern Data Modeling Tutorial
Ref: Java 21 Language Guide , Dev.java — Data-Oriented Programming
Tags: #public #java #oop #data-modeling #tier/core


Overview

Modern Java (Java 17–21+) pairs traditional class-based OOP with algebraic data types built from record, sealed, and exhaustive pattern-matching switch. Choosing the right construct makes invariants explicit at compile time and removes boilerplate.

Choosing a Type Construct

Construct Mutability & Identity Inheritance Best For
class Mutable or immutable; reference identity Open (unless final or sealed) Stateful services, entities with lifecycle, encapsulated mutable state
record Shallowly immutable; value-based equals/hashCode Implicitly final; can implement interfaces Transparent data carriers, DTOs, domain value objects
sealed interface / sealed class Determined by permitted subtypes Closed set via permits Closed variant trees (sum types), protocol messages, AST nodes
enum Fixed singleton instances Implicitly final (per-constant class bodies allowed) Fixed sets of named constants with optional behavior
interface Stateless contract (plus default/static/private methods) Multiple inheritance of type Capabilities, behavioral abstractions, functional interfaces

Compact Constructors & Invariant Validation

Records support a compact constructor that validates or defensively copies components before the compiler assigns them to the private final fields:

import java.util.List;
import java.util.Objects;

public record Order(String id, List<String> items) {
    public Order {
        Objects.requireNonNull(id, "id must not be null");
        if (id.isBlank()) {
            throw new IllegalArgumentException("id must not be blank");
        }
        // Defensive immutable copy prevents caller mutation after construction
        items = List.copyOf(items);
    }
}

Sealed Hierarchies & Exhaustive Pattern Matching

Combining sealed interface, record, and Java 21 switch expressions with record deconstruction gives compile-time exhaustiveness without needing a default branch:

public sealed interface PaymentResult permits Approved, Declined, Pending {}

public record Approved(String transactionId, long amountCents) implements PaymentResult {}
public record Declined(String reasonCode) implements PaymentResult {}
public record Pending(int retryAfterSeconds) implements PaymentResult {}

static String describe(PaymentResult result) {
    return switch (result) {
        case Approved(var txId, var cents) -> "Approved " + txId + " ($" + (cents / 100.0) + ")";
        case Declined(var code)            -> "Declined (" + code + ")";
        case Pending(var waitSec)          -> "Pending, retry in " + waitSec + "s";
    };
}

If a new subtype is added to permits, every exhaustive switch fails to compile until updated.

Composition Over Inheritance

Linked from

Related notes