Sub topic 13
Sealed Interfaces with Records and Enums
In earlier chapters you saw that an enum is a fixed list of constants and a record is a short way to write a class that only carries data. This chapter connects the two. You will learn how a sealed interface lets you say exactly which types belong to a family, and why records and enums fit well inside that family.
You need JDK 17 or later for everything in this chapter.
The Problem: An Open Family of Types
An interface is a list of methods that a class promises to provide. Usually, anyone can implement an interface. That openness is often useful. Sometimes, though, you want a closed group.
Think about shapes in a simple drawing app. You support circles and squares, and nothing else. With a normal interface, any programmer could later add class Triangle implements Shape. Code that expects only circles and squares would then meet a shape it does not handle.
An enum solves the "closed group" problem for simple constants. But an enum constant cannot hold different data for each use. Every Coin.DIME is the same object with the same value. A circle needs its own radius, and a square needs its own side length. You need a closed group of types where each type can carry its own data.
A sealed interface gives you that.
What "Sealed" Means
A sealed interface is an interface that lists the only types allowed to implement it. You add the word sealed before interface. You then name the allowed types after the word permits.
sealed interface Shape permits Circle, Square {}This line says: "Shape has exactly two kinds: Circle and Square." No other class may implement Shape. The compiler enforces the rule.
Here are the new words:
- sealed is a keyword that closes an interface (or class) to outsiders.
- permits is a keyword that starts the list of allowed subtypes.
- A permitted subtype is a type named in that list.
Records as Permitted Subtypes
Each permitted subtype must state how open it is. It must be one of these:
| Modifier | Meaning |
|---|---|
| `final` | No one can extend this type. The family stops here. |
| `sealed` | This type is also closed, with its own `permits` list. |
| `non-sealed` | This type is open again. Anyone may extend it. |
A record is always final. You learned this in "What Records Cannot Do". So a record already meets the rule without any extra word. That is one reason records and sealed interfaces work so well together.
Here is a complete program you can save as Main.java and run with java Main.java:
sealed interface Shape permits Circle, Square {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
public class Main {
static double area(Shape shape) {
if (shape instanceof Circle c) {
return Math.PI * c.radius() * c.radius();
} else if (shape instanceof Square s) {
return s.side() * s.side();
}
throw new IllegalStateException("Unknown shape: " + shape);
}
public static void main(String[] args) {
Shape[] shapes = { new Circle(1.0), new Square(2.0) };
for (Shape shape : shapes) {
System.out.println(shape + " has area " + area(shape));
}
}
}Output:
Circle[radius=1.0] has area 3.141592653589793
Square[side=2.0] has area 4.0The area method uses instanceof Circle c. This checks whether shape is a Circle and, if it is, gives you a variable c of type Circle. The throw line at the end is still needed here, because an if chain cannot prove to the compiler that every case is covered. The next chapter shows how a switch can remove that line.
What Happens If Someone Breaks the Rule
Suppose you add this class to the same program:
record Triangle(double base, double height) implements Shape {}The compiler rejects it. The error says that the class is not allowed to extend the sealed type Shape, because it is not listed in the permits clause. To add triangles, you must change the Shape declaration itself:
sealed interface Shape permits Circle, Square, Triangle {}This is the main benefit. Adding a new kind of shape is a deliberate change in one visible place. It cannot happen quietly in some other file.
Leaving Out the permits List
If the sealed interface and all its subtypes are in the same source file, you may leave out permits. The compiler then treats every type in that file that implements the interface as permitted.
sealed interface Shape {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}This means the same thing as the earlier version. Many people still write permits because it lets a reader see the whole family on one line.
Enums as Permitted Subtypes
An enum can also implement a sealed interface. Every enum is implicitly final, unless one of its constants has its own class body. In that case Java makes the enum sealed automatically. Either way, the rule is met, so you never write final or sealed on an enum.
Mixing enums and records in one family is useful when some members carry data and some do not. Imagine commands for a small robot. "Move 5 steps" needs a number. "Stop" and "Pause" need nothing.
sealed interface Command permits Move, Turn, SimpleCommand {}
record Move(int steps) implements Command {}
record Turn(int degrees) implements Command {}
enum SimpleCommand implements Command { STOP, PAUSE }
public class Main {
static String describe(Command command) {
if (command instanceof Move m) {
return "Move " + m.steps() + " steps";
} else if (command instanceof Turn t) {
return "Turn " + t.degrees() + " degrees";
} else if (command == SimpleCommand.STOP) {
return "Stop now";
} else if (command == SimpleCommand.PAUSE) {
return "Pause for a moment";
}
throw new IllegalStateException("Unknown command: " + command);
}
public static void main(String[] args) {
Command[] program = {
new Move(5),
new Turn(90),
SimpleCommand.PAUSE,
new Move(2),
SimpleCommand.STOP
};
for (Command c : program) {
System.out.println(describe(c));
}
}
}Output:
Move 5 steps
Turn 90 degrees
Pause for a moment
Move 2 steps
Stop nowEach part does the job it suits best:
MoveandTurnare records because each use carries its own number.STOPandPAUSEare enum constants because there is only ever one of each, and they carry no data.Commandties them together into one closed family. A method can accept anyCommandand know the full list of possibilities.
Adding Shared Methods
A sealed interface is still an interface. It can declare methods that every permitted type must provide. Records and enums can both implement them.
sealed interface Shape permits Circle, Square {
double area();
}
record Circle(double radius) implements Shape {
public double area() {
return Math.PI * radius * radius;
}
}
record Square(double side) implements Shape {
public double area() {
return side * side;
}
}
public class Main {
public static void main(String[] args) {
Shape s = new Square(3.0);
System.out.println(s.area()); // 9.0
}
}The area method must be public in each record. Interface methods are public, and an implementation cannot make them less visible.
So you now have two ways to give a family its behavior:
| Approach | Where the code lives | Good when |
|---|---|---|
| Interface method | Inside each record or enum | Each type knows how to do the job itself |
| Outside method with checks | In one separate method | You want all the logic for one task in one place |
Both are fine. The sealed interface helps the second approach the most, because the compiler knows the full list of types. In the next chapter, a switch uses that list to check that you handled every case.
Common Mistakes
Other mistakes beginners often make:
- Naming a type in
permitsthat does not implement the interface. Every listed type must really implement it. - Putting subtypes in another package without modules. Keep them in the same package as the sealed interface.
- Using
non-sealedwithout a reason. It opens the family again and gives up the main benefit. Use it only when you really want outsiders to add types under that branch. - Expecting a sealed interface to replace an enum. If no member carries its own data, a plain enum is simpler.
When to Reach for a Sealed Interface
Use a sealed interface when all three of these are true:
- The set of kinds is fixed, and you want the compiler to guard it.
- At least some kinds carry different data.
- You want code that can safely handle "every kind" of the thing.
If only the first is true, use an enum. If none are true, a normal interface is fine.
Exercise
You are modeling payment methods. A payment is either Cash (no data), a Card with a card number (String), or a BankTransfer with an account ID (String). Write a sealed interface Payment and its permitted types, using records and an enum where each fits best.
Show answer
sealed interface Payment permits Card, BankTransfer, SimplePayment {} then record Card(String number) implements Payment {} then record BankTransfer(String accountId) implements Payment {} then enum SimplePayment implements Payment { CASH }. Card and BankTransfer are records because each one carries its own data. Cash carries no data, so it is a single enum constant. Records and enums are already final, so no extra modifier is needed.
Exercise
A teammate writes class Hexagon implements Shape {} in the same package, where Shape is declared as sealed interface Shape permits Circle, Square {}. What happens, and what two changes would make it compile as a closed member of the family?
Show answer
The compiler rejects it because Hexagon is not listed in the permits clause. To fix it, add Hexagon to the list (permits Circle, Square, Hexagon) and mark the class final (final class Hexagon implements Shape {}), or make it a record, which is final automatically.
Exercise
Why does the area method that uses an if chain with instanceof still need a final throw statement, even though Shape is sealed?
Show answer
An if/else chain is not checked for completeness. The compiler does not use the permits list to prove that every case returned a value, so the method needs a statement at the end that returns or throws. A switch over a sealed type can be checked for completeness, which the next chapter covers.