Records and Sealed Classes in Java: Runnable Examples and Rules

Learn when to use a Java record and when to seal a hierarchy. Compile two complete examples, trace their output, and fix the mistakes learners often make.

KnowledgeGate Team

Exam prep & CS education

Updated 13 Nov 20266 min read
Records and Sealed Classes in Java: Runnable Examples and Rules

A record is often described too loosely as a shorter class, and a sealed type is mistaken for another form of final: a record models a fixed set of values, while a sealed parent controls which types may join a hierarchy. For interview revision, Java 8 to Java 21 Features Interviewers Actually Ask keeps the Payment hierarchy deliberately minimal beside lambdas, streams, Optional and virtual threads. Constructor validation, traced fee output and compile-time failure cases turn that sketch into the executable model below. You should already be comfortable with classes and interfaces; the Coding & Skills category provides a broader prerequisite path.

Records and sealed types solve different design problems

A record is a compact data-carrier declaration. In record StudentResult(String name, int score), Java provides private final component fields, accessors named name() and score(), canonical construction, and value-based equals, hashCode, and toString methods.

The components cannot be reassigned after construction. That does not make every referenced object deeply immutable. If a component holds a mutable list, the list may still change unless the constructor makes a defensive copy.

A sealed class or interface is a closed parent that names its permitted direct subtypes. A record answers, "What values make up this object?" A sealed declaration answers, "Which implementations belong to this family?"

Point

Record

Sealed type

Purpose

Model a fixed data aggregate

Control a type family

Syntax

record StudentResult(...)

sealed interface Payment permits ...

Inheritance effect

Cannot be extended

Restricts direct subtypes

Generated members

Accessors and object methods

None merely because it is sealed

Typical use

Results, commands, coordinates

Payments, states, expression trees

Build and run a validated StudentResult record

Save this one-file program as RecordsDemo.java:

java
record StudentResult(String name, int score) {
    StudentResult {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("name is required");
        }
        if (score < 0 || score > 100) {
            throw new IllegalArgumentException("score must be 0..100");
        }
    }

    String grade() {
        if (score >= 75) return "Distinction";
        if (score >= 60) return "First";
        if (score >= 40) return "Pass";
        return "Fail";
    }
}

public class RecordsDemo {
    public static void main(String[] args) {
        StudentResult asha = new StudentResult("Asha", 82);
        StudentResult ravi = new StudentResult("Ravi", 58);

        System.out.println(asha);
        System.out.println(asha.name() + " -> " + asha.grade());
        System.out.println(ravi.name() + " -> " + ravi.grade());

        try {
            new StudentResult("Neha", 104);
        } catch (IllegalArgumentException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Compile and run it:

Code
javac RecordsDemo.java
java RecordsDemo

The output is:

Code
StudentResult[name=Asha, score=82]
Asha -> Distinction
Ravi -> Pass
score must be 0..100

The compact constructor receives name and score, checks them, and completes before Java assigns them to the generated fields. An exception therefore prevents an invalid object from becoming available. Record accessors follow component names, so access is asha.name(), not asha.getName().

Construction flow for new StudentResult("Asha", 82): the inputs pass the compact-constructor checks, then grade() returns Distinction.

Customise a record without claiming deep immutability

A record may contain methods. Add this method inside StudentResult:

java
StudentResult withScore(int newScore) {
    return new StudentResult(name, newScore);
}

Then StudentResult improved = asha.withScore(91); leaves asha.score() at 82 and makes improved.score() 91. Both grades are Distinction. The method returns a new value instead of mutating the old one.

For a component that refers to a collection, copy it explicitly:

java
import java.util.ArrayList;
import java.util.List;

record Team(String name, List<String> members) {
    Team {
        members = List.copyOf(members);
    }
}

List<String> input = new ArrayList<>(List.of("Mira", "Kabir"));
Team team = new Team("Blue", input);
input.add("Zoya");
System.out.println(team.members().size()); // 2
team.members().add("Noor");                // UnsupportedOperationException

List.copyOf disconnects the stored list from later edits to input and exposes an unmodifiable list. This is shallow immutability: the record fixes its component references, but you must still reason about referenced values, just as you do when studying Java string immutability and reference behaviour.

Sealed hierarchy rules

The shape sealed interface Payment permits CardPayment, UpiPayment, CashPayment says that only those listed direct subtypes may implement Payment. Every ordinary permitted subtype must also say how inheritance continues. final stops its branch, sealed allows only another named set of branches, and non-sealed reopens that branch to ordinary extension. A record is already non-extendable, so it can be a closed permitted implementation.

Run a sealed Payment example with records

Save the second complete program as SealedDemo.java:

java
sealed interface Payment permits CardPayment, UpiPayment, CashPayment {
    int amount();
}

record CardPayment(String last4, int amount) implements Payment {}
record UpiPayment(String vpa, int amount) implements Payment {}

final class CashPayment implements Payment {
    private final int amount;

    CashPayment(int amount) {
        this.amount = amount;
    }

    public int amount() {
        return amount;
    }
}

public class SealedDemo {
    static int fee(Payment payment) {
        if (payment instanceof CardPayment card) {
            return card.amount() * 2 / 100;
        }
        return 0;
    }

    public static void main(String[] args) {
        Payment[] payments = {
            new CardPayment("4242", 1500),
            new UpiPayment("asha@upi", 1500),
            new CashPayment(500)
        };

        for (Payment payment : payments) {
            System.out.println(
                payment.getClass().getSimpleName()
                    + " amount=" + payment.amount()
                    + ", fee=" + fee(payment)
            );
        }
    }
}

Run javac SealedDemo.java, followed by java SealedDemo. The card fee is 1500 * 2 / 100 = 3000 / 100 = 30; the other branches return zero.

Code
CardPayment amount=1500, fee=30
UpiPayment amount=1500, fee=0
CashPayment amount=500, fee=0

Now try final class CryptoPayment implements Payment { public int amount() { return 700; } }. It fails at compile time because CryptoPayment is not in the Payment permits list.

Sealed Payment hierarchy permitting CardPayment with fee 30, UpiPayment with fee 0 and CashPayment; CryptoPayment hits a compile error.

Fix common record and sealed-type mistakes

Error

Reason

Correction

Add a non-static instance field to a record

Record state must come from components

Add a component or compute the value

Write asha.score = 90

The component field is private and final

Create a new record, perhaps through withScore

Call getScore()

Record accessors are not JavaBean getters

Call score()

Expect a List component to become immutable

The reference may point to mutable state

Use the List.copyOf pattern from Team

Use a record for evolving state

Records suit value-oriented data

Use a class when identity or mutation is central

Omit a direct subtype from permits

The parent closes the direct subtype set

Add the subtype deliberately

Leave an ordinary permitted class unmodified

It must declare its inheritance policy

Mark it final, sealed, or non-sealed

Sealing is not access control. Package or module placement rules constrain the hierarchy, while public and package-private still determine ordinary visibility.

Practise code-reading and design distinctions

Check 1: What does new StudentResult("Ravi", 58).grade() return? Answer: Pass, because 58 reaches the score >= 40 branch.

Check 2: Why does new StudentResult("Neha", 104) throw before an object is available? Answer: The compact constructor rejects 104 before generated field assignment completes.

Check 3: Does CryptoPayment compile? Answer: No, it is not a permitted direct subtype.

Next, add record BankTransfer(String accountSuffix, int amount) implements Payment {} and add BankTransfer to permits. Under the current fee method, new BankTransfer("9012", 2000) has fee 0 because it is not a CardPayment. Then call ravi.withScore(67): Ravi's old grade is Pass, while the new record's grade is First. Learners needing more syntax repetition can practise classic Java programs before attempting these edits.

Short version and next step

Records make fixed data aggregates concise. Compact constructors protect invariants. Sealed parents restrict direct implementations. Records and sealed types work well together in closed, value-oriented models.

Choose a record only after checking component mutability. Choose a sealed hierarchy only when the domain truly has a controlled set of variants. Continue with the Java Programming course for broader language practice. When you are ready to apply Java to problem solving and placement preparation, follow it with Data Structures and Algorithms Using Java.