GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev — Sealed classes for type hierarchies | java.evolved
Language
Intermediate
Sealed classes for type hierarchiesRestrict which classes can extend a type — enabling exhaustive switches. Code Comparison
✕ Java 8
// Anyone can extend Shape
public abstract class Shape { }
public class Circle extends Shape { }
public class Rect extends Shape { }
// unknown subclasses possible
✓ Java 17+
public sealed interface Shape
permits Circle, Rect {}
public record Circle(double r)
implements Shape {}
public record Rect(double w, double h)
implements Shape {}
See a problem with this code? Let us know.
Why the modern way wins
🔐
Controlled hierarchyOnly permitted subtypes can extend — no surprise subclasses. ✅
Exhaustive matchingThe compiler verifies switch covers all cases, no default needed. 📐
Algebraic data typesModel sum types naturally — sealed + records = ADTs in Java. Old Approach
Open Hierarchy
Modern Approach
sealed permits
Since JDK
17
Difficulty
Intermediate
JDK Support
Sealed classes for type hierarchies
Available
Widely available since JDK 17 LTS (Sept 2021) How it works
Sealed classes define a closed set of subtypes. The compiler knows all possible cases, enabling exhaustive pattern matching without a default branch. Combined with records, they model algebraic data types. Related Documentation
Proof
Related patterns
Language
Beginner
Switch expressionsJava 8
String msg;
switch (day) {
case MONDAY:
msg = "Start";
break;
case FRIDAY:
msg = "End";
break;
default:
msg = "Mid";
}
Java 14+
String msg = switch (day) {
case MONDAY -> "Start";
case FRIDAY -> "End";
default -> "Mid";
};
JDK 14+
→
Language
Intermediate
Module import declarationsJava 8
import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; Java 25+
import module java.base; // All of java.util, java.io, java.nio // etc. available in one line
JDK 25+
→
Language
Intermediate
Pattern matching in switchJava 8
String format(Object obj) {
if (obj instanceof Integer i)
return "int: " + i;
else if (obj instanceof Double d)
return "double: " + d;
else if (obj instanceof String s)
return "str: " + s;
return "unknown";
}
Java 21+
String format(Object obj) {
return switch (obj) {
case Integer i -> "int: " + i;
case Double d -> "double: " + d;
case String s -> "str: " + s;
default -> "unknown";
};
}
JDK 21+
→
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |