Records, Sealed, Immutable Classes ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-11-28

Records, Sealed, Immutable Classes. Practical Tasks

The Order class has all its fields private final, no setters, and is declared final, and yet an order still changes: someone added an item to the list they passed to the constructor. The first exercise below is built around this bug. It is hard to grasp from a description, but once you reproduce it and fix it yourself, you remember it for a long time.

This page collects Java exercises on records, sealed classes and immutable objects. There are three hands-on exercises, one for each lesson of the module: an immutable class with defensive copies, a record with a compact constructor and record patterns, and a sealed hierarchy with a switch that has no default. The exercises follow the order of the lessons, and each one builds on the previous one. Every exercise has a hint, and the task text gives the expected output and the compiler messages you should see.

What to review first

Each exercise practices one lesson. If you get stuck, go back to the lesson in the table.

Topic Lesson Exercise on this page
The five rules of an immutable class, defensive copies, with-methods Immutable classes in Java Immutable Order class
Compact constructor, extra constructors, record patterns Java records Record Price
permits, non-sealed, switch over a sealed type Sealed classes and interfaces Sealed payment hierarchy

Immutable Order Class: Defensive Copies and with-Methods

  1. Create an Order class with the fields String id, java.util.Date createdAt and List<String> items, and make it immutable: a final class, all fields private final, no setters.
  2. In the constructor, check id with Objects.requireNonNull(). Store a defensive copy of the date (new Date(createdAt.getTime())) and only after copying check that the date is not in the future. Store the list with List.copyOf() and reject an empty order by throwing IllegalArgumentException.
  3. Write the getters: getCreatedAt() returns a copy of the date, getItems() returns the field itself. In a comment, explain why the list needs no copy in the getter while the Date does.
  4. Instead of a setter, add a withItem(String item) method that returns a new Order with the item added. Override toString().
  5. In main, prove the class is immutable. After creating an order, change the original list and the original date, call getCreatedAt().setTime(...) and getItems().add(...) (expect UnsupportedOperationException), and confirm the order did not change. Then call order.withItem("jam") first without an assignment and then with one, and compare the output.
  6. Replace Date with LocalDate and remove the copies that are no longer needed. In a comment, list which of the five rules of an immutable class now hold by themselves.

Hint

Copy the date before validating it, not after: otherwise another thread can change the original Date between the check and the copy. And do not use createdAt.clone(): Date is not final, so the caller can pass a subclass with an overridden clone().

Record Price: Compact Constructor, Factories and Record Patterns

  1. Declare record Price(long cents, String currency): a price in cents and a three-letter currency code.
  2. In the compact constructor, check that currency is not null and cents is not negative. Convert the currency code to upper case (currency = currency.toUpperCase();) and check that it is exactly three Latin letters. In a comment, explain why you cannot write this.currency = ... here.
  3. Add an extra constructor Price(long cents) that passes the currency "EUR" through this(...), and a static factory Price.zero(String currency).
  4. Add a plus(Price other) method: it throws IllegalArgumentException when the currencies differ and returns a new price otherwise.
  5. Check the generated methods. Print new Price(1050, "usd") (expect Price[cents=1050, currency=USD]). Put two prices with equal components into a HashSet and confirm the set size is 1.
  6. Write a method String describe(Object o) that uses a record pattern in instanceof. For a zero price it returns "free (EUR)", for other prices a string like "10.50 USD", and for any other object "not a price".

Nuance

In a compact constructor you assign to the parameter, not to the field: the compiler fills in the fields itself after the constructor body. That is why the normalized currency.toUpperCase() value ends up both in the field and in equals(): new Price(1, "usd") and new Price(1, "USD") are equal.

A Sealed Payment Hierarchy and a switch Without default

  1. Declare sealed interface PaymentMethod permits Card, Cash, BankTransfer. Make Card(String number, boolean premium) and Cash() records, make BankTransfer a regular class with the non-sealed modifier, and extend it with a SepaTransfer class.
  2. Remove the non-sealed modifier from BankTransfer, write the compiler error (sealed, non-sealed or final modifiers expected) in a comment, and put the modifier back. Explain why the record subtypes need no modifier.
  3. Write a method long fee(PaymentMethod p, long amount) using a switch with pattern matching and no default. A premium card costs 0 (a record pattern with when), a regular card 2% of the amount, cash 0, and any transfer, SepaTransfer included, 50. For an amount of 10000 and the four payment methods, the output must be 200 0 0 50.
  4. Add a new record Crypto(String wallet) to permits and confirm that fee no longer compiles (the switch expression does not cover all possible input values). Add a branch for Crypto. In a comment, explain why it is better not to write default in a switch like this.
  5. Try declaring record GiftCard(String code) implements PaymentMethod without adding it to permits, and write the compiler message in a comment.

Hint

The order of the branches matters: case Card(String n, boolean premium) when premium must come before case Card c. If you swap them, the compiler reports this case label is dominated by a preceding case label.

When you write the programs, follow the code style checklist.

How to check your solution

Code that compiles and prints the right result does not yet prove that a class is immutable or that a hierarchy is closed. In these exercises you check a solution by trying to break it: change the object from outside, create an invalid object, add an extra subtype.

Immutable class. After creating the object, change everything you passed to the constructor: the original list, the original date. Change everything the getters returned too. If toString() still prints the same as right after creation, the defensive copies are in place. Trying to change the list through the getter must end with UnsupportedOperationException, not pass silently.

Record. Pass bad data to the constructor: a negative amount, null, the currency "dollars". Each call must throw IllegalArgumentException or NullPointerException with a clear message. Check equality too: new Price(1050, "usd").equals(new Price(1050, "USD")) must be true, because the compact constructor normalizes the currency code.

Sealed hierarchy. Here the compiler does the checking. Add a new type to permits, and the method with a switch that has no default stops compiling until you add a branch for it. If the code still compiles, your switch has a branch left that silently accepts any type.

Frequently asked questions

Which exercise should I start with?

In order: the immutable Order, then record Price, then the sealed payment hierarchy. Each exercise builds on the previous one: a record is a short way to write an immutable class, and the subtypes of the sealed interface in the third exercise are records themselves.

Which Java version do I need?

The first exercise works on Java 10 and later because it uses List.copyOf(). Records need Java 16, sealed classes need Java 17, and a switch with pattern matching, record patterns and when needs Java 21. The easiest choice is to solve all three on Java 21 or 25.

Can I write Order as a record right away in the first exercise?

You can, but then the exercise loses its point: a record makes the class final and the fields private final and has no setters on its own. The exercise is there so you apply all five rules of an immutable class by hand. Once it works, rewrite Order as a record with a defensive copy in the compact constructor and compare the amount of code.

Do interviewers ask exercises like these?

Yes. "How to create an immutable class" is one of the most common Java Core interview questions. Records and sealed classes come up for roles that use Java 17 or later: how a record differs from a regular class and Lombok @Value, why non-sealed exists, and why a switch over a sealed type needs no default.

Comments

Please log in or register to have a possibility to add comment.