Java Sealed Class Switch Example

1. Introduction

In this blog post, we explore how to use Java Sealed Classes in conjunction with the Switch statement. Sealed Classes, a feature introduced in Java 17, provide a way to define classes with restricted hierarchies. Utilizing them with Switch statements enhances type safety and predictability in your code.

Definition

A sealed class in Java restricts which other classes can extend it. When used with a Switch statement, it allows the compiler to ensure that all possible cases are covered, eliminating the need for a default case and enhancing type safety.

2. Program Steps

1. Define a sealed class with a few subclasses.

2. Create a method that uses a Switch statement on instances of these subclasses.

3. Demonstrate how the Switch statement handles different subclass instances.

3. Code Program

// Sealed class definition
sealed interface Shape permits Circle, Rectangle {
    double area();
}

final class Circle implements Shape {
    private final double radius;
    Circle(double radius) { this.radius = radius; }
    public double area() { return Math.PI * radius * radius; }
}

final class Rectangle implements Shape {
    private final double length, width;
    Rectangle(double length, double width) { this.length = length; this.width = width; }
    public double area() { return length * width; }
}

public class SealedClassSwitchExample {
    public static String classifyShape(Shape shape) {
        return switch (shape) {
            case Circle c -> "Circle with area: " + c.area();
            case Rectangle r -> "Rectangle with area: " + r.area();
        };
    }

    public static void main(String[] args) {
        Shape circle = new Circle(5);
        Shape rectangle = new Rectangle(4, 3);

        System.out.println(classifyShape(circle));
        System.out.println(classifyShape(rectangle));
    }
}

Output:

Circle with area: 78.53981633974483
Rectangle with area: 12.0

Explanation:

1. Shape is a sealed interface with Circle and Rectangle as its permitted subclasses.

2. Both Circle and Rectangle implement the Shape interface and provide their specific area calculations.

3. The classifyShape method uses a switch expression to determine the type of Shape and returns a string with the shape's description and area.

4. In the main method, instances of Circle and Rectangle are passed to classifyShape, demonstrating how the switch expression handles each specific subclass.

5. The output shows that the switch expression correctly identifies each shape and calculates its area, showcasing the power of sealed classes with type-safe switch expressions in Java.


Comments