When you have a class hierarchy with a fixed set of subclasses, you’ll see the benefits of using sealed classes in Java 17. Without sealed classes, you might end up with a brittle and hard-to-maintain class hierarchy. For instance, when you have 200 concurrent users hitting a single-threaded service, you’ll see the importance of using sealed classes to restrict instantiation and ensure thread safety.

TL;DR: In this tutorial, you’ll learn how to implement sealed classes in Java 17 to restrict instantiation and improve code quality. You’ll see examples of how to use sealed classes to create a fixed set of subclasses and ensure thread safety.

## Prerequisites To follow along with this tutorial, you’ll need: * Java 17 or later * Spring Boot 2.5 or later * Maven or Gradle * A code editor or IDE The following Maven dependency is required:

 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> 

## Understanding Sealed Classes Sealed classes in Java 17 are a new feature that allows you to restrict instantiation of a class to a fixed set of subclasses. This is useful when you have a class hierarchy with a fixed set of subclasses and you want to ensure that no other subclasses can be created.

 +---------------+ | Sealed Class | +---------------+ | | v +---------------+ | Subclass 1 | +---------------+ | | v +---------------+ | Subclass 2 | +---------------+ 

The following table compares sealed classes with other class types:

Class Type Description
Sealed Class A class that can be extended by a fixed set of subclasses.
Final Class A class that cannot be extended.
Abstract Class A class that can be extended by any number of subclasses.

For more information on Java class types, see More Java Tutorials. ## Implementing Sealed Classes To implement a sealed class in Java 17, you need to use the `sealed` keyword. Here are the steps: ### Step 1: Define the Sealed Class Define a sealed class using the `sealed` keyword.

 public sealed class Vehicle permits Car, Truck, Motorcycle { // code here } 

### Step 2: Define the Subclasses Define the subclasses that are permitted to extend the sealed class.

 public final class Car extends Vehicle { // code here } public final class Truck extends Vehicle { // code here } public final class Motorcycle extends Vehicle { // code here } 

### Step 3: Use the Sealed Class Use the sealed class and its subclasses in your code.

 public class Main { public static void main(String[] args) { Vehicle vehicle = new Car(); // code here } } 

The expected output will be:

 Vehicle is a Car 

## Complete Working Example Here is a complete working example of a sealed class in Java 17:

 // Vehicle.java public sealed class Vehicle permits Car, Truck, Motorcycle { public void drive() { System.out.println("Vehicle is driving"); } } // Car.java public final class Car extends Vehicle { @Override public void drive() { System.out.println("Car is driving"); } } // Truck.java public final class Truck extends Vehicle { @Override public void drive() { System.out.println("Truck is driving"); } } // Motorcycle.java public final class Motorcycle extends Vehicle { @Override public void drive() { System.out.println("Motorcycle is driving"); } } // Main.java public class Main { public static void main(String[] args) { Vehicle vehicle = new Car(); vehicle.drive(); } } 

To test the sealed class, you can use a sample curl/HTTP request: “`bash curl -X GET ‘http://localhost:8080/vehicle’ “` The response will be: “`json { “vehicle”: “Car” } “` ## Common Mistakes and How to Fix Them Here are some common mistakes and how to fix them: ### Mistake 1: Not Using the `sealed` Keyword If you forget to use the `sealed` keyword, you will get a compiler error.

 // WRONG - causes compiler error public class Vehicle permits Car, Truck, Motorcycle { // code here } 

The error message will be: “`java error: sealed class ‘Vehicle’ must be declared with the ‘sealed’ keyword “` To fix this, add the `sealed` keyword:

 // FIXED public sealed class Vehicle permits Car, Truck, Motorcycle { // code here } 

For more information on Java compiler errors, see Java Algorithms. ## Performance and Production Tips Here are some performance and production tips:

Production tip: Use the `sealed` keyword to restrict instantiation of a class to a fixed set of subclasses. This can improve performance by reducing the number of possible subclasses.

Production tip: Use the `final` keyword to prevent subclasses from being extended further. This can improve performance by reducing the number of possible subclasses.

For more information on Java performance optimization, see Mastering SQL. ## Testing Here is an example of a JUnit 5 test for the sealed class:

 import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class VehicleTest { @Test public void testDrive() { Vehicle vehicle = new Car(); vehicle.drive(); assertEquals("Car is driving", vehicle.toString()); } } 

The expected output will be:

 Car is driving 

For more information on JUnit 5 testing, see Java Interview Questions. ## Key Takeaways Here are the key takeaways: * Use the `sealed` keyword to restrict instantiation of a class to a fixed set of subclasses. * Use the `final` keyword to prevent subclasses from being extended further. * Use sealed classes to improve performance by reducing the number of possible subclasses. * Use JUnit 5 testing to verify the behavior of sealed classes. * Use SOLID Design Principles in Java to design robust and maintainable class hierarchies.

Read Next

Pillar Guide: Java Tutorials Hub — explore the full learning path.

Source Code on GitHub
java-examples — Clone, Star & Contribute

You Might Also Like

Java 25 New Features and Enhancements Complete Guide
Mastering Java 21 Pattern Matching for Switch and Record Patterns
Java 26 Project Panama Foreign Function API Improvements: A Comprehensive Guide (2026)


Leave a Reply

Your email address will not be published. Required fields are marked *