Sobes.tech
Junior — Middle

Explain what it means to restrict an interface using the 'sealed' keyword in Java or similar languages.

sobes.tech AI

Answer from AI

The keyword sealed in Java (starting from version 15 as a preview and officially from 17) is used to restrict inheritance of an interface or class. It allows explicitly specifying which classes or interfaces can inherit or implement the given interface or class.

This helps control and limit the type hierarchy, increasing safety and predictability of the code.

Example:

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

public final class Circle implements Shape {
    // implementation
}

public final class Rectangle implements Shape {
    // implementation
}

Here, the Shape interface can only be implemented by the Circle and Rectangle classes. Other classes cannot implement Shape.