Sub topic 13
Sealed types, enums, abstract classes and open interfaces compared
This chapter assumes you know how sealed types work. That means the sealed, permits, final and non-sealed keywords, records, enums, and pattern-matching switch on Java 21 or later. It does not teach those again. It helps you choose between four ways to model "a thing that comes in several kinds".
The four tools and what each one fixes
Each tool fixes a different property of the design. Pick the tool by deciding which of these properties you need.
- Enum: fixes the set of instances. There is exactly one object per constant, and every constant has the same fields.
- Sealed type: fixes the set of subtypes. Each subtype can have its own fields, and any number of instances.
- Abstract class: fixes nothing about who may extend it. It provides shared state and partial implementation. Anyone with access can subclass it unless you also seal it.
- Open interface: fixes only a contract. Any class, anywhere, can implement it.
| Question | Enum | Sealed type | Abstract class | Open interface |
|---|---|---|---|---|
| Who can add variants? | Only the enum's author | Only the listed subtypes | Anyone with access | Anyone |
| Variants carry different data? | No, one shape for all constants | Yes, per subtype | Yes, per subclass | Yes, per implementer |
| Many instances per variant? | No, one each | Yes | Yes | Yes |
| Exhaustive `switch` without `default`? | Yes | Yes | No | No |
| Shared mutable state and constructors? | Limited (fields and a private constructor) | Yes, if the root is a sealed abstract class | Yes | No (constants only) |
| Multiple inheritance of type? | Can implement interfaces | A subtype can implement other interfaces | One superclass only | Many interfaces |
| Typical use | Days, states, modes | Results, ASTs, commands, events | Template or base class | Plugins, callbacks, SPIs |
Enums: a closed set of values
Use an enum when the variants are values, not kinds of data. A Level is always one of three singletons, and nothing about HIGH differs in shape from LOW.
public class EnumDemo {
enum Level { LOW, MEDIUM, HIGH }
static int weight(Level level) {
return switch (level) {
case LOW -> 1;
case MEDIUM -> 5;
case HIGH -> 10;
};
}
public static void main(String[] args) {
for (Level level : Level.values()) {
System.out.println(level + " -> " + weight(level));
}
}
}An enum gives you things a sealed hierarchy does not: values(), valueOf, EnumSet, EnumMap, a stable ordinal() and name(), safe serialization by name, and == comparison. If you modeled Level as a sealed interface with three records, you would lose all of that and gain nothing.
The enum breaks down when one variant needs data the others lack. If HIGH needs a String escalationContact and LOW needs nothing, you end up with nullable fields on every constant. That is the signal to move to a sealed hierarchy.
Open interfaces: extension points
Use an open interface when you expect code you cannot see to implement it. The caller depends only on the contract and never asks "which kind is this?".
public class OpenDemo {
interface Plugin {
String name();
void run();
}
static void runAll(Iterable<? extends Plugin> plugins) {
for (Plugin p : plugins) {
System.out.println("running " + p.name());
p.run();
}
}
public static void main(String[] args) {
Plugin hello = new Plugin() {
public String name() { return "hello"; }
public void run() { System.out.println("hello, world"); }
};
runAll(java.util.List.of(hello));
}
}Here runAll never inspects the concrete type, so it is correct for implementations that do not exist yet. Sealing this interface would remove the extension point. A switch over an open interface cannot be exhaustive. The compiler cannot know all implementers, so you would need a default branch.
Abstract classes: shared state and behavior
Use an abstract class when subclasses share fields, constructors or non-trivial method bodies. Interfaces cannot hold instance state, and records cannot extend another class.
An abstract class alone is open. Any code that can see it can subclass it, and each subclass can then be subclassed again unless it is final. Adding sealed closes it. That combination fits when you want shared state and a known set of subclasses:
sealed abstract class Account permits Checking, Savings {
private final String id;
protected long balanceCents;
Account(String id, long balanceCents) {
this.id = id;
this.balanceCents = balanceCents;
}
String id() { return id; }
abstract long monthlyFeeCents();
}
final class Checking extends Account {
Checking(String id, long balance) { super(id, balance); }
long monthlyFeeCents() { return balanceCents < 100_000 ? 500 : 0; }
}
final class Savings extends Account {
Savings(String id, long balance) { super(id, balance); }
long monthlyFeeCents() { return 0; }
}A switch over Account is exhaustive with two cases. The accounts are mutable objects with identity, so records would be the wrong choice here.
Sealed types: closed sets of differently shaped data
Use a sealed hierarchy when the set of kinds is known, each kind carries its own data, and callers need to handle every kind. The usual root is a sealed interface, and the usual subtypes are records.
The next program combines a record, an enum and a switch in one hierarchy. The enum is a permitted subtype of a sealed interface. That is allowed because enums are implicitly final unless they have constant bodies, in which case they are implicitly sealed.
public class SealedDemo {
sealed interface Payment permits Card, Transfer, Cash {}
record Card(String last4, int installments) implements Payment {}
record Transfer(String iban) implements Payment {}
enum Cash implements Payment { INSTANCE }
static String describe(Payment payment) {
return switch (payment) {
case Card c -> "card ending " + c.last4() + " in " + c.installments() + " parts";
case Transfer t -> "transfer to " + t.iban();
case Cash c -> "cash";
};
}
public static void main(String[] args) {
System.out.println(describe(new Card("4242", 3)));
System.out.println(describe(new Transfer("DE89 3704 0044 0532 0130 00")));
System.out.println(describe(Cash.INSTANCE));
}
}Cash has no data and needs one instance, so an enum constant fits it. The other two kinds carry data, so they are records. A sealed hierarchy lets you mix these freely.
How to decide
Three further questions refine the answer:
- Do callers branch on the kind, or just call a method? If every caller only calls
shape.area(), polymorphism through an open interface works and aswitchis not needed. If callers do different things per kind, a sealed hierarchy and aswitchkeep that logic in one place. - Who owns the operations? With an open interface, new variants are easy and new operations are hard, since each operation must be added to every implementer. With a sealed hierarchy and
switch, new operations are easy because you write a new method with oneswitch. New variants are hard, because everyswitchmust change. - Is this a public API? Sealing a public type is a promise that you will control its variants. If outside code might legitimately need to implement it, leave it open.
What breaks when the set changes
The point of closing a set is that the compiler tells you when it changes. Compare the cost of adding one variant in each design.
| Change | Enum | Sealed type | Open interface |
|---|---|---|---|
| Add a variant | Every `switch` without `default` stops compiling | Same | Nothing breaks, but code that handled "all kinds" may miss it |
| Add an abstract method | Not applicable, constants share one type | Every subtype must implement it | Every implementer breaks, unless you use a `default` method |
| Remove a variant | Callers using it stop compiling | Same | Implementers remain valid |
If the hierarchy is compiled in separate pieces, a stale class file can still run after a permitted subtype is added. A switch compiled against the old set then throws MatchException at runtime when it meets the new subtype. Recompile every consumer when you change a sealed hierarchy.
Combining the tools
The choices are not exclusive. Some common combinations:
- Sealed root, open leaf. Mark one permitted subclass
non-sealedto keep a controlled set of categories while allowing extension inside one of them. Switches stay exhaustive because they cover the non-sealed class and all its subclasses through that one case. - Sealed interface, enum leaves. Group related enums under one sealed interface when an operation accepts values from several enums. Each enum must be listed in
permits, or declared in the same compilation unit whenpermitsis omitted. - Sealed interface, open implementation detail. Keep the public type sealed and implement each permitted record with helper abstract classes or interfaces internally. Callers see a closed set, and your code still reuses logic.
Common mistakes
- Using a sealed hierarchy for plain constants. Three records with no fields are an enum written the hard way. You lose
values(),EnumMapand name-based serialization. - Using an enum with nullable fields. If half the constants set a field to
null, the variants have different shapes and you want a sealed hierarchy. - Sealing a type that users must extend. Frameworks, plugin systems and test doubles often need to implement your types. Sealing breaks them.
- Writing
default"just in case". It disables the compiler check described above. - Forgetting the placement rules. Permitted subclasses must be in the same module, or in the same package when the code is in the unnamed module. A hierarchy that must span packages in a plain classpath project cannot be sealed.
Exercise
You are writing a library with a Logger type. Application authors will provide their own loggers that write to files, databases or cloud services. Should Logger be an enum, a sealed interface or an open interface? Give one reason for your choice.
Show answer
An open interface. Logger implementations are an extension point that outside code must supply, and a sealed type or enum would forbid that. Callers also only call methods such as log(...) and never branch on the kind, so exhaustive switch is not needed.
Exercise
A Shipment can be Pending, InTransit (with a carrier name and tracking number) or Delivered (with a delivery timestamp). Which tool fits best, and why does an enum fall short?
Show answer
A sealed interface Shipment with three records. The variants carry different data (nothing, carrier and tracking number, a timestamp). Enum constants all share one shape, so you would need nullable fields on every constant. The sealed hierarchy also gives an exhaustive switch with no default, so adding a new state makes every unhandled switch fail to compile.