Java / Java 21 Coding Standards Interview Questions
When should you use a sealed interface instead of an enum?
An enum fits when every variant is a simple, stateless (or identically-shaped) constant - DayOfWeek or Status are classic examples, where each value needs no unique fields beyond what every other value also has.
public sealed interface PaymentMethod permits CreditCard, BankTransfer {} public record CreditCard(String last4, String network) implements PaymentMethod {} public record BankTransfer(String iban) implements PaymentMethod {}
A sealed interface is the better fit when each variant needs genuinely different data - a CreditCard carries a card number and network, while a BankTransfer carries an IBAN, and forcing both into a single enum would mean either a bloated enum with fields that are null for some constants, or a separate lookup table keyed by the enum value.
The decision rule under coding standards is simple: if the variants only differ in identity (which one is it), use an enum; if the variants carry different shapes of data, use a sealed hierarchy of records so each variant's data is fully typed and required, not optional.
More Related questions...