深入理解 Java 密封类(Sealed Classes):从设计到实战
Deep Dive into Java Sealed Classes: From Design to Practice
| iDev Engineering | 2026-09-01T10:54:59
Java 密封类是模式匹配的基石,让你精确控制类的继承层级。本文通过领域建模和状态机实战讲解密封类的正确用法。
Java sealed classes are the foundation of pattern matching. This article explains their proper usage through domain modeling and state machine examples.
什么是密封类密封类(Sealed Classes)允许你精确控制哪些类可以继承它。这不是简单的访问控制,而是一种领域建模工具。基本语法public sealed interface Shape permits Circle, Rectangle, Triangle { } public record Circle(double radius) implements Shape {} public record Rectangle(double w, double h) implements Shape {} public record Triangle(double a, double b, double c) implements Shape {}配合模式匹配double area(Shape shape) { return switch (shape) { case Circle c -> Math.PI * c.radius() * c.radius(); case Rectangle r -> r.w() * r.h(); case Triangle t -> { double s = (t.a() + t.b() + t.c()) / 2; yield Math.sqrt(s * (s-t.a()) * (s-t.b()) * (s-t.c())); } }; // 编译器保证穷尽性,不需要 default }实战:订单状态机密封类非常适合建模有限状态集合。编译器会在 switch 中检查是否覆盖了所有可能的状态,新增状态时未处理的地方会编译报错。最佳实践优先使用 record 作为密封类的子类密封接口比密封类更灵活结合 switch 模式匹配发挥最大威力
What are Sealed ClassesSealed classes let you precisely control which classes can extend them. Combined with pattern matching, they enable exhaustive switch expressions that the compiler verifies at compile time.Best PracticesPrefer records as sealed class subtypesSealed interfaces are more flexible than sealed classesCombine with switch pattern matching for maximum power