亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
1. Records: Immutable Data Carriers
When to Use Records
Key Rules
Adding Behavior (Optional)
2. Sealed Classes: Controlled Inheritance
Why Use Sealed Classes?
Syntax Example
Use with Pattern Matching (Modern Java Combo)
3. Combining Records and Sealed Classes
Example: Expressions in a Calculator
Final Thoughts
首頁 Java java教程 使用現(xiàn)代爪哇的記錄和密封課程

使用現(xiàn)代爪哇的記錄和密封課程

Jul 30, 2025 am 02:37 AM
java 編程

使用記錄(records)來創(chuàng)建不可變數(shù)據(jù)載體,它自動生成構(gòu)造函數(shù)、訪問器、equals、hashCode和toString方法,適用于DTO或簡單域模型;2. 使用密封類(sealed classes)限制繼承體系,通過permits關(guān)鍵字明確允許的子類,實(shí)現(xiàn)封閉的類型層次,提升switch表達(dá)式的窮盡性與安全性;3. 將記錄與密封類結(jié)合,可構(gòu)建類型安全、結(jié)構(gòu)清晰、易于模式匹配的數(shù)據(jù)模型,如代數(shù)數(shù)據(jù)類型或表達(dá)式樹,從而提高代碼的可讀性、可維護(hù)性和正確性。

Using Records and Sealed Classes in Modern Java

Java has evolved significantly over the years, and with Java 16 (as a standard feature), records and sealed classes were introduced to make it easier to model immutable data and control class hierarchies. These features are especially useful in modern Java development for writing cleaner, safer, and more maintainable code.

Using Records and Sealed Classes in Modern Java

Let’s break down how and why to use them.


1. Records: Immutable Data Carriers

A record is a special kind of class designed to model immutable data. It automatically generates constructors, accessors, equals(), hashCode(), and toString() methods based on the components you declare.

Using Records and Sealed Classes in Modern Java

When to Use Records

Use records when you’re creating a class whose main purpose is to hold data — like DTOs (Data Transfer Objects), configuration holders, or simple domain models.

public record Person(String name, int age) {}

That single line gives you:

Using Records and Sealed Classes in Modern Java
  • A constructor: Person(String name, int age)
  • Public accessor methods: name() and age()
  • Proper equals(), hashCode(), and toString() implementations

Key Rules

  • Records are implicitly final and can’t be extended.
  • The fields are private final and cannot be modified.
  • You can add static fields, methods, or even custom constructors (with validation), but the core components remain immutable.

Adding Behavior (Optional)

You can enhance a record with additional methods:

public record Person(String name, int age) {
    public boolean isAdult() {
        return age >= 18;
    }
}

? Best Practice: Use records for data-centric classes. If you need behavior, inheritance, or mutability, stick with regular classes.


2. Sealed Classes: Controlled Inheritance

Sealed classes let you restrict which classes can extend or implement them. This is useful when you want to define a closed set of types — like in domain modeling or pattern matching scenarios.

Why Use Sealed Classes?

They allow you to:

  • Model algebraic data types (ADTs)
  • Make switch expressions more exhaustive and safe
  • Prevent unexpected subclasses from appearing elsewhere

Syntax Example

public sealed abstract class Shape permits Circle, Rectangle, Triangle {
    // common behavior
}

final class Circle extends Shape {
    public final double radius;
    public Circle(double radius) { this.radius = radius; }
}

final class Rectangle extends Shape {
    public final double width, height;
    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }
}

final class Triangle extends Shape {
    public final double a, b, c;
    public Triangle(double a, double b, c) {
        this.a = a; this.b = b; this.c = c;
    }
}

Here:

  • permits Circle, Rectangle, Triangle explicitly lists allowed subclasses.
  • Each permitted class must be final, sealed, or non-sealed (a new keyword).

? The non-sealed modifier allows a subclass to be open for extension even within a sealed hierarchy.

Use with Pattern Matching (Modern Java Combo)

Sealed classes shine when used with switch expressions and pattern matching:

double area(Shape shape) {
    return switch (shape) {
        case Circle c -> Math.PI * c.radius * c.radius;
        case Rectangle r -> r.width * r.height;
        case Triangle t -> { // Heron's formula
            double s = (t.a   t.b   t.c) / 2;
            yield Math.sqrt(s * (s - t.a) * (s - t.b) * (s - t.c));
        }
    };
}

Because Shape is sealed and all subtypes are known, the compiler knows the switch is exhaustive — no default needed.


3. Combining Records and Sealed Classes

One of the most powerful modern Java patterns is using records with sealed classes to model data variants cleanly.

Example: Expressions in a Calculator

public sealed interface Expr permits Constant, Add, Multiply {}

record Constant(double value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Multiply(Expr left, Expr right) implements Expr {}

Now you can write a recursive evaluator:

double evaluate(Expr expr) {
    return switch (expr) {
        case Constant c -> c.value();
        case Add a -> evaluate(a.left())   evaluate(a.right());
        case Multiply m -> evaluate(m.left()) * evaluate(m.right());
    };
}

This approach gives you:

  • Immutability via records
  • Type safety via sealed hierarchy
  • Clean, readable code
  • Exhaustive pattern matching

Final Thoughts

Records and sealed classes are not just syntactic sugar — they represent a shift toward modeling data more precisely and safely in Java.

  • ? Use records for transparent, immutable data carriers.
  • ? Use sealed classes/interfaces when you want to define a closed type hierarchy.
  • ? Combine them to build expressive domain models, especially for trees, expressions, or state machines.

They work best with other modern Java features like pattern matching (instanceof and switch) and enhance code clarity and correctness.

Basically, if you're still writing POJOs with getters, setters, and toString() boilerplate — or allowing unlimited inheritance — it’s time to give records and sealed classes a try.

以上是使用現(xiàn)代爪哇的記錄和密封課程的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

用雅加達(dá)EE在Java建立靜止的API 用雅加達(dá)EE在Java建立靜止的API Jul 30, 2025 am 03:05 AM

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

Java項(xiàng)目管理Maven的開發(fā)人員指南 Java項(xiàng)目管理Maven的開發(fā)人員指南 Jul 30, 2025 am 02:41 AM

Maven是Java項(xiàng)目管理和構(gòu)建的標(biāo)準(zhǔn)工具,答案在于它通過pom.xml實(shí)現(xiàn)項(xiàng)目結(jié)構(gòu)標(biāo)準(zhǔn)化、依賴管理、構(gòu)建生命周期自動化和插件擴(kuò)展;1.使用pom.xml定義groupId、artifactId、version和dependencies;2.掌握核心命令如mvnclean、compile、test、package、install和deploy;3.利用dependencyManagement和exclusions管理依賴版本與沖突;4.通過多模塊項(xiàng)目結(jié)構(gòu)組織大型應(yīng)用并由父POM統(tǒng)一管理;5.配

CSS暗模式切換示例 CSS暗模式切換示例 Jul 30, 2025 am 05:28 AM

首先通過JavaScript獲取用戶系統(tǒng)偏好和本地存儲的主題設(shè)置,初始化頁面主題;1.HTML結(jié)構(gòu)包含一個(gè)按鈕用于觸發(fā)主題切換;2.CSS使用:root定義亮色主題變量,.dark-mode類定義暗色主題變量,并通過var()應(yīng)用這些變量;3.JavaScript檢測prefers-color-scheme并讀取localStorage決定初始主題;4.點(diǎn)擊按鈕時(shí)切換html元素上的dark-mode類,并將當(dāng)前狀態(tài)保存至localStorage;5.所有顏色變化均帶有0.3秒過渡動畫,提升用戶

CSS下拉菜單示例 CSS下拉菜單示例 Jul 30, 2025 am 05:36 AM

是的,一個(gè)常見的CSS下拉菜單可以通過純HTML和CSS實(shí)現(xiàn),無需JavaScript。1.使用嵌套的ul和li構(gòu)建菜單結(jié)構(gòu);2.通過:hover偽類控制下拉內(nèi)容的顯示與隱藏;3.父級li設(shè)置position:relative,子菜單使用position:absolute進(jìn)行定位;4.子菜單默認(rèn)display:none,懸停時(shí)變?yōu)閐isplay:block;5.可通過嵌套實(shí)現(xiàn)多級下拉,結(jié)合transition添加淡入動畫,配合媒體查詢適配移動端,整個(gè)方案簡潔且無需JavaScript支持,適合大

如何將Java MistageDigest用于哈希(MD5,SHA-256)? 如何將Java MistageDigest用于哈希(MD5,SHA-256)? Jul 30, 2025 am 02:58 AM

要使用Java生成哈希值,可通過MessageDigest類實(shí)現(xiàn)。1.獲取指定算法的實(shí)例,如MD5或SHA-256;2.調(diào)用.update()方法傳入待加密數(shù)據(jù);3.調(diào)用.digest()方法獲取哈希字節(jié)數(shù)組;4.將字節(jié)數(shù)組轉(zhuǎn)換為十六進(jìn)制字符串以便讀?。粚τ诖笪募容斎?,應(yīng)分塊讀取并多次調(diào)用.update();推薦使用SHA-256而非MD5或SHA-1以確保安全性。

Python Parse Date String示例 Python Parse Date String示例 Jul 30, 2025 am 03:32 AM

使用datetime.strptime()可將日期字符串轉(zhuǎn)換為datetime對象,1.基本用法:通過"%Y-%m-%d"解析"2023-10-05"為datetime對象;2.支持多種格式如"%m/%d/%Y"解析美式日期、"%d/%m/%Y"解析英式日期、"%b%d,%Y%I:%M%p"解析帶AM/PM的時(shí)間;3.可用dateutil.parser.parse()自動推斷未知格式;4.使用.d

VSCODE設(shè)置。JSON位置 VSCODE設(shè)置。JSON位置 Aug 01, 2025 am 06:12 AM

settings.json文件位于用戶級或工作區(qū)級路徑,用于自定義VSCode設(shè)置。1.用戶級路徑:Windows為C:\Users\\AppData\Roaming\Code\User\settings.json,macOS為/Users//Library/ApplicationSupport/Code/User/settings.json,Linux為/home//.config/Code/User/settings.json;2.工作區(qū)級路徑:項(xiàng)目根目錄下的.vscode/settings

Python獲取MAC地址示例 Python獲取MAC地址示例 Jul 30, 2025 am 02:59 AM

使用uuid模塊可跨平臺獲取本機(jī)第一個(gè)網(wǎng)卡的MAC地址,無需第三方庫,通過uuid.getnode()轉(zhuǎn)換為標(biāo)準(zhǔn)格式;2.使用subprocess調(diào)用系統(tǒng)命令如ipconfig或ifconfig,結(jié)合正則提取所有網(wǎng)卡MAC地址,適用于需獲取多個(gè)網(wǎng)卡信息的場景;3.使用第三方庫getmac,安裝后調(diào)用get_mac_address()即可獲取MAC,支持按接口或IP查詢,但需額外依賴;綜上,若無需外部庫則推薦uuid方法,若需靈活獲取多網(wǎng)卡信息可用subprocess方案,允許安裝依賴時(shí)getma

See all articles