Skip to content

Grokem · https://www.grokem.com/programming/programming-languages/java-records-sealed-classes-and-pattern-matching-explained-with-examples

Programming LanguagesExplainerIntermediate level

Java records, sealed classes and pattern matching explained with examples

Records model data, sealed types close an inheritance hierarchy, and pattern matching branches on the exact type. This explainer shows how the three fit together, with one runnable example and the compile errors you will meet.

Pankaj Nigam

Technical Writer

Published
  • 6 min read
  • 0 sec

Your progress
  1. Java records, sealed classes and pattern matching explained with examples6 min(finished)
    0%

What you will learn

5
  • Explain what a record generates for you and what it does not
  • Describe how a sealed type closes an inheritance hierarchy
  • Use type patterns with instanceof and switch
  • Explain why sealed types and pattern matching give exhaustive checks
  • Decide when a record or a sealed type is the wrong tool

Modern Java adds three features that solve one problem: modelling data and choices without boilerplate. Records describe data. Sealed classes and interfaces list every allowed subtype. Pattern matching takes a value apart by its type. Each helps alone, but together they let the compiler check your branching for you.

This page explains each idea from first principles and ends with one complete program you can compile and run. Exact release availability differs by JDK, so check your JDK's official documentation for which of these features your version supports.

What problem do these three features solve together?

Most programs hold two kinds of things: plain data (a point, an order line, a response) and a fixed set of alternatives (a payment is a card or a transfer). Before these features you wrote long classes for the data and left the alternatives open to anyone.

The three features split the work:

  • Records remove the boilerplate of data classes.
  • Sealed types state that the set of alternatives is closed.
  • Pattern matching lets you branch on which alternative you hold.

Because the set is closed, the compiler knows when you have handled every case.

What is a record?

A record is a concise carrier for data. You declare the components once, and Java generates the constructor, the accessors, equals, hashCode and toString for you.

That means two records with the same component values are equal. You do not write that comparison yourself, and you cannot forget to update it when a field changes.

In the example below, Point has two components, x and y. You read them with p.x() and p.y(), not with getX().

java
record Point(int x, int y) {}

Are records really immutable?

A record's fields are set once at construction and never reassigned. There are no setters. That makes a record easy to reason about, to share between threads and to use as a map key.

The immutability is shallow. If a component holds a mutable object, such as a list, the record does not freeze that list. When a component is mutable, copy it or choose an immutable type.

What is a sealed class or interface?

A sealed type restricts who may extend or implement it. You list the permitted subtypes, and the compiler rejects any other class that tries to join the hierarchy.

Ordinary inheritance is open: anyone can add a subclass later. A sealed type explicitly closes the hierarchy, so you know every possible subtype at the time you write the code.

sealed interface Shapepermits Circle, Rectanglerecord Circlerecord Rectangleclass Triangle(not permitted)compile error
A sealed type accepts only the subtypes it lists.

In the diagram, only the listed records can implement Shape. A third class is rejected at compile time.

java
sealed interface Shape permits Circle, Rectangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}

What is pattern matching?

Pattern matching tests a value against a shape and, if it fits, gives you a typed variable in one step. You no longer test the type and then cast.

With instanceof, the pattern variable p is already a Point inside the if block. With switch, each case can name a type and bind a variable, and the switch returns a value.

The exact forms your JDK accepts depend on its release. Check your JDK's language documentation if the compiler rejects a pattern.

java
static String describe(Object value) {
    if (value instanceof Point p) {
        return "Point at " + p.x() + "," + p.y();
    }
    return "Something else";
}

Why do sealed types and pattern matching work so well together?

A switch over a sealed type can be exhaustive. The compiler knows the full list of subtypes, so it can verify that your cases cover all of them.

This gives you two benefits:

  • You need no default branch that silently swallows new cases.
  • When you add a new permitted subtype, every switch that misses it stops compiling, so the compiler shows you each place to update.

Records fit this pattern because the alternatives are usually small data carriers. A sealed interface with record implementations reads like a list of named choices, each with its own data.

How does it look in one complete program?

The program below defines a Point record, a sealed Shape with two record implementations, and uses both an instanceof pattern and a switch pattern. Save it as ModernJavaDemo.java, then compile and run it.

The area method has no default branch. The compiler accepts it only because the two cases cover every permitted subtype.

java
public class ModernJavaDemo {

    record Point(int x, int y) {}

    sealed interface Shape permits Circle, Rectangle {}
    record Circle(double radius) implements Shape {}
    record Rectangle(double width, double height) implements Shape {}

    static double area(Shape shape) {
        return switch (shape) {
            case Circle c -> Math.PI * c.radius() * c.radius();
            case Rectangle r -> r.width() * r.height();
        };
    }

    static String describe(Object value) {
        if (value instanceof Point p) {
            return "Point at " + p.x() + "," + p.y();
        }
        return "Something else";
    }

    public static void main(String[] args) {
        Point a = new Point(1, 2);
        Point b = new Point(1, 2);
        System.out.println(a.equals(b));
        System.out.println(describe(a));
        System.out.println(describe("text"));
        System.out.printf("%.2f%n", area(new Circle(2.0)));
        System.out.printf("%.2f%n", area(new Rectangle(3.0, 4.0)));
    }
}
bash
javac ModernJavaDemo.java
java ModernJavaDemo

What happens when you add a new shape?

Add a Triangle record to the permits list and to nothing else. The area method no longer covers every subtype, so the compiler reports an error instead of letting a missing case fail at run time.

This is the main payoff of closing the hierarchy: the compiler tracks the cases so you do not have to.

When should you not use them?

Do not use a record when the object needs changing state, or when identity matters more than values. A record models a value, not a long-lived entity with a life cycle.

Do not seal a type that outside code must extend, such as a library extension point. Sealing says the set is final, so it suits domain models you control.

Do not treat shallow immutability as deep immutability. Check mutable components yourself.


Glossary

Record
A concise data carrier whose constructor, accessors, equals, hashCode and toString are generated from its components.
Sealed type
A class or interface that lists exactly which subtypes may extend or implement it.
Pattern matching
Testing a value against a type pattern and binding a typed variable when it matches.
Exhaustive switch
A switch whose cases cover every possible value, which the compiler can verify for sealed types.
Shallow immutability
The fields cannot be reassigned, but objects they refer to may still change.

Frequently asked questions

Does a record generate equals for me?

Yes. A record generates its constructor, accessors, equals, hashCode and toString, so two records with the same component values are equal.

Are Java records immutable?

Their fields cannot be reassigned after construction. The immutability is shallow, so a mutable object inside a record can still change.

What does a sealed class do?

It restricts which classes may extend it. You list the permitted subtypes, and the compiler rejects any others.

Why does a switch over a sealed type need no default?

The compiler knows every permitted subtype. If your cases cover them all, the switch is exhaustive.

Which JDK release do I need?

This page does not state a release. Check your JDK's official release notes for records, sealed types and pattern matching.

Next steps

  • Model one of your own domain choices, such as payment methods, as a sealed interface with record implementations
  • Read your JDK's official language documentation for the exact pattern forms it supports
  • Replace an instanceof and cast chain in your code with a switch over a sealed type

From Grokem: https://www.grokem.com/programming/programming-languages/java-records-sealed-classes-and-pattern-matching-explained-with-examples

Finished this article?

How did this strike you?

Be the first to react – it is anonymous.

Community

Questions about this?

Ask in Questions and help and get help from other readers.

Ask a questionBrowse Questions and help

Comments

No comments yet. Share what worked for you, or ask a question.

Keep learning

Picked for this article

Related reading, discussions and learning paths on the same subject.

All in Programming Languages

Choose what we may use. You can change this at any time with “Privacy choices” at the foot of every page. Details are in the Cookie policy and the Privacy policy.

Strictly necessary

Remembers your theme, the lessons you marked as done and this choice. It stays on your device, tracks nothing and cannot be switched off.

Always on
What exactly is collected, and why

Google Analytics

Collects
The pages you view, your device and browser type, your language, how you reached the site and your approximate location (country and city, worked out from your IP address).
Why
To understand which pages and lessons are used, so we can improve them.
Stored
Two cookies, _ga and _ga_<id>, for up to 2 years. Google acts for us; the data is processed by Google, including outside your country.

Grokem’s own counts

Collects
The pages you open and how long you stay, how far you scroll, where you came from, your device type, browser, screen size, language and time zone. Your IP address is turned into a code that changes every day; it is never stored as it is.
Why
To see how long lessons are read and where readers leave. Not shared with anyone.
Stored
A random visitor ID, a visit ID and the time of your last page view in your browser’s storage (gr_vid, gr_sid, gr_last). No name or email is attached.