Java Sealed Classes and Interfaces
sealed interface Payment permits Card, Wallet, Cash is a guest list javac enforces, so a Voucher is a compile error. Account shows final, sealed and non-sealed children, Delivery records each carry their own data and fee, and a switch over Payment needs no default.
What you will learn
- Close a type family with sealed and permits so javac rejects anything else
- Choose final, sealed or non-sealed for each permitted subclass
- Model real cases as records under one sealed interface
- Write a switch over a sealed type that needs no default
Before you start
- Java records
- Java interfaces
A sealed class is a class family with a fixed guest list. You write the list, and javac, the Java compiler, enforces it.
An interface is open to anyone
Say a Payment interface has three planned kinds: Card, Wallet and Cash. But any class anywhere can implement an interface: GiftCard, Barter, Coupon. Nobody can list every kind of payment. That's what sealed fixes.
package org.studyeasy.s05l02;
import java.util.List;
public class Ex01_SealedPayment {
// The guest list: only these three types may implement Payment
sealed interface Payment permits Card, Wallet, Cash {}
// Records are final already, so they need no extra modifier
record Card(String holder, double amount) implements Payment {}
record Wallet(String walletId, double amount) implements Payment {}
record Cash(double amount) implements Payment {}
public static void main(String[] args) {
List<Payment> today = List.of(
new Card("Emma Clarke", 250.0),
new Wallet("liam.w@wallet", 80.0),
new Cash(40.0));
for (Payment p : today) {
System.out.println(p);
}
}
}
Card[holder=Emma Clarke, amount=250.0]
Wallet[walletId=liam.w@wallet, amount=80.0]
Cash[amount=40.0]
sealed and permits give the full list: only Card, Wallet and Cash may implement Payment. All three are records, which are final already, so they join with no extra keyword. Add record Voucher(double amount) implements Payment {} and javac refuses: class is not allowed to extend sealed class: Payment (as it is not listed in its 'permits' clause). It's a compile error, not a surprise at run time. To add a type, edit the permits line first.
Sealed classes too
// A sealed class names its subclasses...
static sealed abstract class Account permits Savings, Loan, Current {}
// ...and each one decides how the family goes on
static final class Savings extends Account {} // ends here
static sealed class Loan extends Account permits HomeLoan {} // new list
static final class HomeLoan extends Loan {}
static non-sealed class Current extends Account {} // open again
static class BusinessCurrent extends Current {} // allowed
Savings extends Account
HomeLoan extends Loan
BusinessCurrent extends Current
This part is slightly tricky. Savings is final, so nobody extends it. Loan is sealed again, with its own list, so HomeLoan may extend Loan (but not Account directly). Current is non-sealed, which opens it up again, so BusinessCurrent extends it without permission. Leave all three off a permitted class and javac says sealed, non-sealed or final modifiers expected. Records need none, since they're final.
Model the real cases
// Every delivery option, and each one carries only the data it needs
sealed interface Delivery permits Standard, Express, Pickup {
default double fee() { return 0; } // Pickup is free
}
record Standard(int km) implements Delivery {
public double fee() { return 30 + 2 * km; }
}
record Express(int km) implements Delivery {
public double fee() { return 99 + 5 * km; }
}
record Pickup(String store) implements Delivery {}
List<Delivery> orders = List.of(new Standard(12), new Express(4),
new Pickup("Downtown"));
for (Delivery d : orders) {
System.out.println(d + " -> fee " + d.fee());
}
Standard[km=12] -> fee 54.0
Express[km=4] -> fee 119.0
Pickup[store=Downtown] -> fee 0.0
The sealed line lists every way an order can travel, and each case holds only its own data: kilometres for Standard and Express, a store name for Pickup. Pickup has no fee of its own, so it uses the default, 0. One call, d.fee(), and each object gives the right fee (30 + 2 × 12 is 54). This is the kind of sealed interface you'll see most often.
Why not an enum? An enum gives a fixed set of values, one object each with the same fields, so there's nowhere for 12 km or a store name to go. A sealed interface gives a fixed set of types, and each object carries its own data. Same shape for every case: enum. Different data, closed list: sealed with records.
A switch with no default
// No default branch: javac checks that every permitted type has a case
static String receipt(Payment p) {
return switch (p) {
case Card c -> c.holder() + " paid " + c.amount() + " by card";
case Wallet w -> w.walletId() + " paid " + w.amount() + " by wallet";
case Cash c -> "Counter received " + c.amount() + " in cash";
};
}
Emma Clarke paid 250.0 by card
liam.w@wallet paid 80.0 by wallet
Counter received 40.0 in cash
The switch picks a case by the type of p. case Card c means "if it's a Card, call it c" (more in pattern matching). There's no default: javac matches each permitted type to a case and finds all three covered. Add Voucher to the permits list but not the switch, and javac says the switch expression does not cover all possible input values. It points at every switch that hasn't caught up.
Recap
| You write | Compiles? |
|---|---|
class Oval implements Shape (not permitted) | no |
class Ring extends Circle (Circle is final) | no |
class Box extends Square (Square is a record) | no |
final class Triangle extends Polygon (Polygon permits Triangle) | yes |
class Star extends Custom (Custom is non-sealed) | yes |
Close the family with sealed and permits, let each subtype pick final, sealed or non-sealed, and a switch over the records needs no default.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java Classes and Objects: One Blueprint, Many Cars
Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.
Java Constructors and the this Keyword
A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.
Java Instance Methods, Getters, Setters and toString
Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.
Java static: Fields, Methods and Blocks Shared by the Whole Class
A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.
