0Pricing
Java Academy · Lesson

Sealed with Records

Model closed hierarchies.

Sealed with Records is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Sealed Plus Records

Sealed interfaces and records are a perfect pair. The sealed interface defines a closed set of cases; each record is one concrete, immutable case. Together they model algebraic data types.

Records Are Implicitly final

A record is automatically final, so it satisfies the rule that permitted subtypes must be final, sealed, or non-sealed. No extra modifier is needed.

A Closed Shape Hierarchy

Model shapes as records implementing a sealed interface, each carrying its own data.

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

    public static void main(String[] args) {
        Shape s = new Rectangle(3, 4);
        System.out.println(s);
    }
}

Adding Behavior

The sealed interface can declare methods that every record implements, giving polymorphism over the closed set.

public class Main {
    sealed interface Shape permits Circle, Rectangle {
        double area();
    }
    record Circle(double radius) implements Shape {
        public double area() { return Math.PI * radius * radius; }
    }
    record Rectangle(double width, double height) implements Shape {
        public double area() { return width * height; }
    }

    public static void main(String[] args) {
        Shape s = new Circle(2);
        System.out.printf("Area: %.2f%n", s.area());
    }
}

Free Equality and toString

Records generate equals, hashCode, and toString automatically. Two records with the same components are equal, which is ideal for value modeling.

public class Main {
    sealed interface Shape permits Circle {}
    record Circle(double radius) implements Shape {}

    public static void main(String[] args) {
        Circle a = new Circle(5);
        Circle b = new Circle(5);
        System.out.println(a.equals(b));
        System.out.println(a);
    }
}

Modeling Results

A common pattern is a sealed result type with a success record and a failure record, replacing nullable returns or exceptions for expected outcomes.

public class Main {
    sealed interface Result permits Ok, Err {}
    record Ok(int value) implements Result {}
    record Err(String message) implements Result {}

    static Result parse(String s) {
        try { return new Ok(Integer.parseInt(s)); }
        catch (NumberFormatException e) { return new Err("bad number: " + s); }
    }

    public static void main(String[] args) {
        System.out.println(parse("42"));
        System.out.println(parse("oops"));
    }
}

Compact Constructors for Validation

Records can validate their inputs in a compact constructor, keeping each case correct by construction.

public class Main {
    sealed interface Shape permits Circle {}
    record Circle(double radius) implements Shape {
        Circle {
            if (radius < 0) throw new IllegalArgumentException("radius must be >= 0");
        }
    }

    public static void main(String[] args) {
        try { new Circle(-1); }
        catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
    }
}

Recursive Data Models

Because a record can reference the sealed interface, you can build recursive structures like expression trees or linked lists.

public class Main {
    sealed interface Expr permits Num, Add {}
    record Num(int value) implements Expr {}
    record Add(Expr left, Expr right) implements Expr {}

    public static void main(String[] args) {
        Expr e = new Add(new Num(1), new Add(new Num(2), new Num(3)));
        System.out.println(e);
    }
}

Immutability Benefits

Records are shallowly immutable, so a sealed hierarchy of records is easy to reason about, safe to share, and friendly to concurrency. No defensive copying of the records themselves is needed.

Pairing With switch

Sealed records shine with pattern-matching switch: each case can destructure a record and the compiler checks that all cases are covered. That is explored in the patterns course.

A Calculation Over the Model

You can write an interpreter as a method that walks the recursive record tree.

public class Main {
    sealed interface Expr permits Num, Add {}
    record Num(int value) implements Expr {}
    record Add(Expr left, Expr right) implements Expr {}

    static int eval(Expr e) {
        if (e instanceof Num n) return n.value();
        Add a = (Add) e;
        return eval(a.left()) + eval(a.right());
    }

    public static void main(String[] args) {
        Expr e = new Add(new Num(4), new Add(new Num(5), new Num(6)));
        System.out.println(eval(e));
    }
}

Quick Check

Test your understanding of sealed records.

Recap

You learned to combine sealed types with records.

  • Records are implicitly final, so they slot in as permitted subtypes.
  • The sealed interface can declare shared methods.
  • Records give free equality, hashing, and toString.
  • Together they model closed, immutable, possibly recursive data.

Frequently asked questions

Is the “Sealed with Records” lesson free?

Yes — the full text of “Sealed with Records” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Sealed with Records”?

Model closed hierarchies. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Sealed with Records” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Declaring Sealed Types
  2. permits Clause
  3. Sealed with Records
  4. Exhaustive switch on Sealed
← Back to Java Academy