Java Sealed Class Enum Example

1. Introduction

This blog post explores the use of sealed classes in Java in combination with enums. Sealed classes, a feature introduced in Java 17, restrict which other classes can extend them. Using enums with sealed classes provides a robust way to define a finite set of subclasses.

Definition

Sealed classes in Java are used to define classes that can only be extended by certain predefined classes or interfaces. Enums are a type of class in Java that define a fixed set of constants. Combining sealed classes with enums offers a type-safe, controlled approach to class hierarchies.

2. Program Steps

1. Define a sealed class.

2. Create an enum that extends the sealed class.

3. Use instances of the enum in an application.

3. Code Program

// Sealed class definition
sealed interface Command permits Command.Mode {
    void execute();

    // Enum that extends the sealed interface
    enum Mode implements Command {
        TURN_ON {
            @Override
            public void execute() {
                System.out.println("The device is turned on.");
            }
        },
        TURN_OFF {
            @Override
            public void execute() {
                System.out.println("The device is turned off.");
            }
        }
    }
}

public class SealedClassEnumExample {
    public static void main(String[] args) {
        Command command = Command.Mode.TURN_ON;
        command.execute();

        command = Command.Mode.TURN_OFF;
        command.execute();
    }
}

Output:

The device is turned on.
The device is turned off.

Explanation:

1. Command is a sealed interface with Mode enum as its permitted subclass.

2. The Mode enum implements Command and defines two constants: TURN_ON and TURN_OFF, each with an overridden execute method.

3. In SealedClassEnumExample, instances of Command.Mode enum are created and used to execute commands.

4. The execute method prints different messages based on the enum constant, demonstrating polymorphic behavior in a controlled environment.

5. This example highlights the use of sealed classes and enums in Java to create a well-defined, type-safe set of behaviors.


Comments