Cosmic Module

J

Qubits of DPK

March 14, 2026

Core Java

Layman Explanation

Normally any class can extend your class. Sealed classes let you say: "ONLY these specific classes are allowed to extend me. Nobody else."
Like a VIP club with a fixed, known guest list.

Real World Analogy

A payment system: only Credit Card, Debit Card, and UPI are valid payment types. No one should be able to add "BitcoinPayment" or "InvalidPayment" as a new type randomly. Sealed classes enforce this.

What is a Sealed Class?

A class that restricts which other classes can extend it using the permits clause.
java
QUBITS OF DPK
1// Sealed class — only these 3 can extend it
2public sealed class Shape
3    permits Circle, Rectangle, Triangle {
4
5    abstract double area();
6}
7
8// Each permitted subclass must be one of:
9// 1. final    — cannot be extended further
10// 2. sealed   — can be extended but with its own permits
11// 3. non-sealed — open for extension by anyone
12
13final class Circle extends Shape {
14    double radius;
15    Circle(double r) { this.radius = r; }
16
17    @Override
18    double area() { return Math.PI * radius * radius; }
19}
20
21final class Rectangle extends Shape {
22    double width, height;
23    Rectangle(double w, double h) { this.width = w; this.height = h; }
24
25    @Override
26    double area() { return width * height; }
27}
28
29final class Triangle extends Shape {
30    double base, height;
31    Triangle(double b, double h) { this.base = b; this.height = h; }
32
33    @Override
34    double area() { return 0.5 * base * height; }
35}

Three Options for Permitted Subclasses

java
QUBITS OF DPK
1// Option 1: final — no further extension
2final class Circle extends Shape { }
3
4// Option 2: sealed — can extend but with restrictions
5sealed class Quadrilateral extends Shape
6    permits Square, Rectangle { }
7
8// Option 3: non-sealed — open to anyone
9non-sealed class CustomShape extends Shape { }
10// Now anyone can extend CustomShape

Sealed Interfaces

java
QUBITS OF DPK
1// Sealed interfaces work the same way
2public sealed interface Payment
3    permits CreditCard, DebitCard, UPI {
4
5    void process(double amount);
6}
7
8final class CreditCard implements Payment {
9    @Override
10    public void process(double amount) {
11        System.out.println("Credit card: " + amount);
12    }
13}
14
15final class UPI implements Payment {
16    @Override
17    public void process(double amount) {
18        System.out.println("UPI: " + amount);
19    }
20}

Power: Sealed Classes + Pattern Matching

java
QUBITS OF DPK
1// Since compiler knows ALL possible subtypes,
2// switch is exhaustive without default!
3Shape shape = new Circle(5.0);
4
5double area = switch (shape) {
6    case Circle c    -> Math.PI * c.radius * c.radius;
7    case Rectangle r -> r.width * r.height;
8    case Triangle t  -> 0.5 * t.base * t.height;
9    // No default needed! Compiler knows all 3 cases covered
10};
11
12System.out.println("Area: " + area);

Production Use Cases

java
QUBITS OF DPK
1// 1. Domain modeling — known set of types
2sealed interface ApiResponse permits Success, Error, Redirect { }
3final class Success implements ApiResponse { int statusCode; String body; }
4final class Error   implements ApiResponse { int code; String message; }
5final class Redirect implements ApiResponse { String location; }
6
7// 2. State machines — known set of states
8sealed interface OrderState
9    permits Pending, Processing, Shipped, Delivered, Cancelled { }
10
11// 3. Expression trees (compilers, calculators)
12sealed interface Expr
13    permits Num, Add, Multiply { }
14record Num(int value) implements Expr { }
15record Add(Expr left, Expr right) implements Expr { }
16record Multiply(Expr left, Expr right) implements Expr { }

️ All Traps

java
QUBITS OF DPK
1// Trap 1 — Permitted subclass must be in same package (or same file)
2// or same module
3
4// Trap 2 — Permitted subclasses must directly extend sealed class
5// Can't skip levels
6
7// Trap 3 — Each permitted subclass MUST declare final/sealed/non-sealed
8class Circle extends Shape { }  // ❌ compile error! Must declare
9final class Circle extends Shape { }  // ✅
10
11// Trap 4 — Can't extend sealed class from outside permits list
12class Pentagon extends Shape { }  // ❌ compile error!

30-Second Interview Answer

"Sealed classes introduced in Java 17 restrict which classes can extend them using the permits clause. Each permitted subclass must be declared as final (no further extension), sealed (restricted extension), or non-sealed (open). This gives developers control over class hierarchies and enables exhaustive pattern matching in switch without a default case since the compiler knows all possible subtypes. Perfect for domain modeling where a fixed set of types is needed, like payment types, API responses, or order states."

Interview Questions & MAANG-Level Answers

Q1. What is a sealed class in Java?
Introduced in Java 17 (JEP 409), a sealed class restricts which other classes can extend it using the permits clause: public sealed class Shape permits Circle, Rectangle, Triangle. Only those listed classes can extend Shape. Any other class trying to extend Shape gets a compile error. Sealed interfaces work the same way. This gives developers explicit control over class hierarchies.
Q2. What are the three options a permitted subclass must choose from?
Every class in the permits list MUST declare one of: (1) final — cannot be extended further. final class Circle extends Shape {}. (2) sealed — can be extended but with its own restricted permits list. sealed class Quadrilateral extends Shape permits Square, Rectangle {}. (3) non-sealed — opens the hierarchy back up to anyone. non-sealed class FreeformShape extends Shape {} — anyone can extend FreeformShape. This is a deliberate escape hatch.
Q3. What is the benefit of sealed classes with pattern matching?
Since the compiler knows ALL possible subtypes of a sealed class, switch expressions can be exhaustive without a default case:
java
QUBITS OF DPK
1sealed interface Shape permits Circle, Rectangle, Triangle {}
2double area(Shape s) {
3    return switch (s) {
4        case Circle c    -> Math.PI * c.radius() * c.radius();
5        case Rectangle r -> r.width() * r.height();
6        case Triangle t  -> 0.5 * t.base() * t.height();
7        // No default needed! Compiler verifies all 3 covered.
8    };
9}
If you add a new permitted subclass (e.g., Pentagon), the compiler flags all switch expressions that need updating — compile-time safety for exhaustive type dispatch.
Q4. What is the difference between sealed and final?
final class: cannot be extended by ANYONE — complete prevention of subclassing. sealed class: can be extended, but ONLY by the explicitly listed permitted classes. Sealed allows a controlled, known set of extensions; final allows none. final is a complete door-lock; sealed is a VIP list.
Q5. Where must permitted subclasses be located?
In Java 17+, permitted subclasses must be in the same package (or same module) as the sealed class. They don't need to be in the same file (though they can be, as unnamed/nested classes). The compiler verifies this at compile time. For single-file sealed hierarchies (e.g., in examples), all classes can be in the same file.