Sealed classes are a feature introduced in Java 17 to limit which classes or interfaces can inherit or implement it. Its core role is to enhance control over inheritance by explicitly declaring allowed subclasses. Specifically: 1. Addresses the problem that the subclasses were not restricted at the language level before; 2. Supports pattern matching (especially when combined with record classes); 3. Use sealed keywords and permits clauses to define allowed subclasses; 4. Subclasses must be declared final, sealed or non-sealed; 5. Applicable to closed type hierarchy, compile-time inspection and domain model design; 6. It should be noted that subclasses must be explicitly inherited in the same module or package. Sealing classes are suitable for scenarios that require strict inheritance control, but should not be abused.
Sealed classes in Java are a feature introduced in Java 17 that lets you restrict which other classes or interfaces can extend or implement them. In simple terms, they give you more control over inheritance by explicitly stating who is allowed to be a subclass.

This is useful when you want to define a class hierarchy that's both closed and well-known — like modeling types where only specific variations should exist.

What Problem Do Sealed Classes Solve?
Before sealed classes, if you wanted to limit which classes could extend yours, you had to rely on documentation or package-private visibility tricks. But there was no real language-level enforcement.
Now, with sealed classes:

- You can explicitly declare which subclasses are allowed.
- You avoid unexpected or unauthorized subclassing.
- It helps make pattern matching with
switch
statements more powerful (especially in combination with records).
For example:
public sealed class Shape permits Circle, Rectangle, Triangle { // ... }
This means only Circle
, Rectangle
, and Triangle
can extend Shape
. No one else.
How to Use Sealed Classes
Using sealed classes involves two main parts: defining the sealed class and declaring its allowed subclasses.
Here's how you do it:
- Use the
sealed
modifier on the class. - Follow it with a
permits
clause listing the allowed subclasses.
Example:
public sealed class Animal permits Cat, Dog, Bird { // common behavior }
Each of those subclasses must then extend Animal
and also be declared as either:
-
final
: If it shouldn't be extended further. -
sealed
: If it allows some subclasses but not all. -
non-sealed
: If it removes any restrictions on its children.
Like this:
public final class Cat extends Animal { }
Or this:
public sealed class Mammal extends Animal permits Human, Monkey { }
When Should You Use Them?
You'll find sealed classes most useful in these situations:
- You're building a closed type hierarchy (eg, expressions in a compiler, game entities).
- You want better compile-time checks for exhaustive pattern matching.
- You're using records and want to combine them with sealed hierarchies for clearer domain models.
They're especially handy when you're writing code like this:
switch(shape) { case Circle c -> {...} case Rectangle r -> {...} case Triangle t -> {...} }
Because the compiler knows exactly which subclasses exist, it can tell you if your switch
is missing a case.
A Few Gotchas to Keep in Mind
There are a few small but important rules when working with sealed classes:
- All permitted subclasses must be in the same module (or package if in the unnamed module).
- Subclasses must explicitly extend the sealed parent.
- The sealing chain must be consistent — if a parent is sealed, each child must follow the same rules.
Also, while sealed classes are powerful, they're not always necessary. If your class hierarchy is open or likely to grow, sticking with a regular class makes more sense.
So unless you have a clear reason to seal a class, don't. But when you do need tight control over inheritance, they're a great tool.
Basically that's it.
The above is the detailed content of What are Sealed Classes in Java?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.
