Java Sealed Class Generic Example

1. Introduction

This blog post delves into the use of sealed classes in Java with a focus on generics. Sealed classes, introduced in Java 17, allow for defining classes with restricted hierarchies. When combined with generics, they offer a powerful way to create type-safe, controlled class structures.

Definition

Sealed classes in Java restrict which other classes can extend them. Generics enable classes, interfaces, and methods to operate on types while providing compile-time type safety. The combination of sealed classes and generics provides a way to define flexible yet controlled type hierarchies.

2. Program Steps

1. Define a sealed class with a generic parameter.

2. Create specific subclasses of the sealed class, utilizing the generic parameter.

3. Demonstrate the use of these generic subclasses.

3. Code Program

// Sealed class with a generic parameter
sealed abstract class Shape<T> permits Circle, Rectangle {
    abstract T area();
}

// Subclass of Shape with a specific generic type
final class Circle extends Shape<Double> {
    private final double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    Double area() {
        return Math.PI * radius * radius;
    }
}

// Another subclass of Shape with a different generic type
final class Rectangle extends Shape<Integer> {
    private final int length, width;

    Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }

    @Override
    Integer area() {
        return length * width;
    }
}

public class SealedClassGenericExample {
    public static void main(String[] args) {
        Shape<Double> circle = new Circle(5.0);
        Shape<Integer> rectangle = new Rectangle(4, 3);

        System.out.println("Circle area: " + circle.area());
        System.out.println("Rectangle area: " + rectangle.area());
    }
}

Output:

Circle area: 78.53981633974483
Rectangle area: 12

Explanation:

1. Shape is a sealed class with a generic parameter T. It specifies Circle and Rectangle as the only classes that can extend it.

2. Circle extends Shape<Double>, meaning its area method returns a Double.

3. Rectangle extends Shape<Integer>, with its area method returning an Integer.

4. In SealedClassGenericExample, instances of Circle and Rectangle are created as Shape types with respective generic types.

5. Calling the area method on these instances demonstrates how generics work with sealed classes, allowing for different return types in a controlled inheritance hierarchy.


Comments