Sealed

Sealed classes and interfaces in Java, introduced in Java 17, provide a way to restrict the inheritance hierarchy of classes and interfaces. When a class or interface is sealed, it specifies which classes or interfaces are allowed to be its direct subclasses or implementers. This enhances the control over the abstraction and encapsulation of types in Java, making the design more robust and secure.

Here's a simple example to illustrate sealed classes and interfaces.

Let's define a sealed interface "Shape" that can be implemented by only specific classes.

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

In this example, the "Shape" interface is sealed, and it specifies that only classes "Circle" and "Rectangle" are permitted to directly implement the "Shape" interface.

Now, let's define the subclasses "Circle" and "Rectangle".

public final class Circle implements Shape {
    private final double radius;

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

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

public final class Rectangle implements Shape {
    private final double width;
    private final double height;

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

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

In this example, "Circle" and "Rectangle" are permitted to implement the "Shape" interface because they are explicitly listed in the "permits" clause of the "Shape" interface declaration.

Now, let's try to define another class "Triangle" that attempts to implement the "Shape" interface.

// error: triangle is not allowed to extend Shape as it is not listed in the permits clause
public final class Triangle implements Shape {
    // implementation omitted
}

Since "Triangle" is not listed in the "permits" clause of the "Shape" interface, attempting to implement the "Shape" interface with "Triangle" will result in a compilation error.

Sealed classes and interfaces provide better control over class hierarchies, allowing developers to specify and enforce constraints on subclassing and implementation relationships, leading to more maintainable and secure codebases.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....