⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

Java 密封类

理解密封类的概念,控制类的继承层次,提高代码安全性与可维护性。 · 难度:入门 · +15XP

密封类概述

Java 17 正式引入密封类(Sealed Classes),允许你指定哪些类或接口可以继承或实现它,从而精确控制类型层次。

基本语法

public sealed class Shape permits Circle, Rectangle, Triangle { }

final class Circle extends Shape { } non-sealed class Rectangle extends Shape { } sealed class Triangle extends Shape permits EquilateralTriangle { }

修饰符说明

修饰符含义
sealed声明为密封类
permits指定允许的子类
final子类不可再被继承
non-sealed子类可被任意继承
sealed子类也是密封的

使用场景

与模式匹配结合

double area = 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();
};

练习提示:定义一个密封接口 PaymentMethod,包含信用卡、PayPal 和银行转账三种实现。

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 133 篇
0 完成
🔥 0