Sealed Class Hierarchy Design
Demonstrates sealed classes and interfaces to create restricted class hierarchies, enabling exhaustive pattern matching and domain modeling with known subtypes.
Code
public class SealedClassHierarchy {
sealed interface Event permits LoginEvent, LogoutEvent, PurchaseEvent, ErrorEvent {
long timestamp();
String userId();
}
record LoginEvent(long timestamp, String userId, String ip) implements Event {
@Override public long timestamp() { return timestamp; }
@Override public String userId() { return userId; }
}
record LogoutEvent(long timestamp, String userId) implements Event {
@Override public long timestamp() { return timestamp; }
@Override public String userId() { return userId; }
}
record PurchaseEvent(long timestamp, String userId, String item, double amount) implements Event {
@Override public long timestamp() { return timestamp; }
@Override public String userId() { return userId; }
}
record ErrorEvent(long timestamp, String userId, String message) implements Event {
@Override public long timestamp() { return timestamp; }
@Override public String userId() { return userId; }
}
static String processEvent(Event event) {
return switch (event) {
case LoginEvent e -> "User " + e.userId() + " logged in from " + e.ip();
case LogoutEvent e -> "User " + e.userId() + " logged out";
case PurchaseEvent e -> "User " + e.userId() + " bought " + e.item() + " for $" + e.amount();
case ErrorEvent e -> "Error for " + e.userId() + ": " + e.message();
};
}
public static void main(String[] args) {
Event[] events = {
new LoginEvent(System.currentTimeMillis(), "alice", "192.168.1.1"),
new PurchaseEvent(System.currentTimeMillis(), "alice", "Widget", 29.99),
new ErrorEvent(System.currentTimeMillis(), "bob", "Invalid session"),
new LogoutEvent(System.currentTimeMillis(), "alice")
};
for (Event event : events) {
System.out.println(processEvent(event));
}
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.