Tsallaka zuwa abun ciki
Justice Tech School

Sealed Classes and Records

A record is an immutable data class with generated constructor, accessors, equals and toString. A sealed interface permits only listed implementations, so switch can be exhaustive.

Example
public class Main {
    sealed interface Shape permits Circle, Rect {}
    record Circle(double r) implements Shape {}
    record Rect(double w, double h) implements Shape {}
    static double area(Shape s) {
        return switch (s) {
            case Circle c -> Math.PI * c.r() * c.r();
            case Rect r -> r.w() * r.h();
        };
    }
    public static void main(String[] args) {
        System.out.printf("%.2f %.1f%n", area(new Circle(1)), area(new Rect(2, 3)));
        System.out.println(new Rect(2, 3));
    }
}

Result

3.14 6.0
Rect[w=2.0, h=3.0]

Exercise

Immutable data class.

 Point(int x, int y) {}

Quiz Test

Why use sealed?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.