JDK17-21特性Sealed类详解
·
Sealed类详解
一、知识概述
Sealed类(密封类)是Java 17正式引入的特性,用于限制类的继承层次,增强类型安全。
1.1 Sealed类核心概念
┌─────────────────────────────────────────────────────────────┐
│ Sealed类核心概念 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 关键字: │
│ - sealed 声明密封类/接口 │
│ - permits 指定允许继承的子类 │
│ - non-sealed 允许任意继承 │
│ - final 禁止继承 │
│ │
│ 特点: │
│ - 控制继承范围 │
│ - 编译时检查 │
│ - 配合模式匹配使用 │
│ │
└─────────────────────────────────────────────────────────────┘
二、Sealed类使用
2.1 基本语法
// ============================================
// Sealed类基本语法
// ============================================
public sealed class Shape permits Circle, Rectangle, Triangle {
// ...
}
public final class Circle extends Shape {
private final double radius;
}
public final class Rectangle extends Shape {
private final double width, height;
}
public non-sealed class Triangle extends Shape {
// 可以被任意继承
}
2.2 Sealed接口
// ============================================
// Sealed接口
// ============================================
public sealed interface Service permits OrderService, UserService {
void process();
}
public final class OrderService implements Service {
@Override
public void process() { /* ... */ }
}
public final class UserService implements Service {
@Override
public void process() { /* ... */ }
}
2.3 模式匹配增强
// ============================================
// Sealed类与模式匹配
// ============================================
public double calculateArea(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.width() * r.height();
case Triangle t -> 0.5 * t.base() * t.height();
// 不需要default,编译器知道所有子类
};
}
三、总结
Sealed类增强了Java的类型系统,与模式匹配配合使用效果更佳。
核心要点
- sealed:声明密封类
- permits:指定子类
- 模式匹配:穷举检查
六、思考与练习
思考题
-
基础题:sealed、non-sealed、final三种修饰符有什么区别?分别在什么场景下使用?
-
进阶题:Sealed类如何配合switch模式匹配实现编译期的穷尽性检查?这种机制带来了哪些安全优势?
-
实战题:在设计领域模型时,什么情况下应该使用Sealed类而不是普通继承?请举例说明。
编程练习
练习:设计一个支付系统,使用Sealed类实现支付方式类型层次:
- 定义sealed接口Payment,permits CreditCard、DebitCard、Alipay、WeChatPay
- 每种支付方式使用Record类实现,包含必要的支付信息
- 实现支付处理器,使用switch模式匹配处理不同支付方式
- 添加支付金额验证逻辑(金额必须大于0)
要求:
- 使用Record实现具体的支付类型
- 在switch中不需要default分支(编译器保证穷尽)
- 实现支付状态枚举(使用sealed interface)
章节关联
- 前置章节:Record类详解
- 后续章节:Virtual Threads详解
- 扩展阅读:代数数据类型(ADT)、访问者模式
📝 下一章预告
下一章将深入探讨Java 21的Virtual Threads(虚拟线程),这是Project Loom的核心特性,将彻底改变Java并发编程的方式。
本章完
更多推荐




所有评论(0)