Sealed Interface in Java 17


In Java, a sealed interface is a feature introduced in Java 17 to restrict which classes can implement an interface. It allows you to specify a limited set of classes that are allowed to implement the interface, thereby controlling the extensibility of your code. This enhances the design by explicitly stating which classes are intended to implement the interface.

Here’s a brief example to demonstrate how sealed interfaces work:

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

// Circle class implementing the sealed interface
final class Circle implements Shape {
    private double radius;

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

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

// Rectangle class implementing the sealed interface
final class Rectangle implements Shape {
    private double length;
    private double width;

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

    public double area() {
        return length * width;
    }
}

// This class cannot extend Shape since it is not permitted
// class Triangle implements Shape { ... }

In this above example, Shape is a sealed interface that permits only Circle and Rectangle classes to implement it. If you try to create a class Triangle and make it implement Shape, it will result in a compile-time error because Triangle is not listed as a permitted subclass of Shape.

Similar Post: Java 17 Sealed Classes

Benefits of sealed interfaces

  1. Encapsulation: Sealed interfaces promote encapsulation by limiting the visibility of the interface to a specific set of classes, thus controlling the access and modification of the interface.
  2. Compiler Checks: Sealed interfaces are checked by the compiler at compile time, ensuring that only permitted classes implement the interface. This helps catch errors early in the development process.
  3. Improved Security: By restricting which classes can implement an interface, sealed interfaces help in preventing unauthorized or unintended implementations, enhancing code security.

References

  1. Sealed Interface- Oracle
  2. JEP 409: Sealed Classes- OpenJDK
  3. Java 17 Sealed Classes

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.