Java Sealed Class Example

1. Introduction

This blog post introduces Java Sealed Classes, a feature introduced in Java 15 as a preview and later finalized in Java 17. Sealed Classes provide a way to control which other classes or interfaces may extend or implement them.

Definition

A sealed class in Java is a class or interface that restricts which other classes or interfaces may extend or implement it. It is declared with the sealed, non-sealed, or final modifier, and it specifies its permitted subclasses directly.

2. Program Steps

1. Declare a sealed class along with its permitted subclasses.

2. Define the permitted subclasses.

3. Create instances of these subclasses and demonstrate polymorphism.

3. Code Program

// Declaring a sealed class
sealed abstract class Shape permits Circle, Rectangle {
    abstract double area();
}

// Final subclass Circle
final class Circle extends Shape {
    private final double radius;

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

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

// Non-sealed subclass Rectangle
non-sealed class Rectangle extends Shape {
    private final double length;
    private final double width;

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

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

public class SealedClassesExample {
    public static void main(String[] args) {
        Shape circle = new Circle(5.0);
        Shape rectangle = new Rectangle(4.0, 3.0);

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

Output:

Area of Circle: 78.53981633974483
Area of Rectangle: 12.0

Explanation:

1. Shape is declared as a sealed class with two permitted subclasses, Circle and Rectangle.

2. Circle is a final class, meaning it cannot be extended further. It provides an implementation for the area method.

3. Rectangle is declared as non-sealed, allowing further extension. It also implements the area method.

4. In the main method, instances of Circle and Rectangle are created and treated as Shape objects.

5. Calling the area method on these instances demonstrates polymorphism and the use of sealed classes to define a restricted hierarchy.


Comments