Sealed Classes and Interfaces in Java

The sealed keyword in Java introduces a controlled inheritance model, allowing a class or interface to be extended only by a specified list of subtypes. This feature provides developers with a way to manage and restrict the hierarchy of classes and interfaces, ensuring that only known and intended subtypes can extend a particular type.

Sealed Classes

A sealed class is a class that can only be subclassed by a predefined set of classes. This is achieved by using the sealed keyword in the class declaration. The subclasses must be declared within the same compilation unit or be non-public in the source file. This restriction helps in maintaining a controlled and predictable class hierarchy.

Example: Sealed Class Pet

Consider the following example of a sealed class Pet:

public abstract sealed class Pet {
    private final String name;
 
    protected Pet(String name) {
        this.name = name;
    }
 
    public String name() {
        return name;
    }
 
    public static final class Cat extends Pet {
        public Cat(String name) {
            super(name);
        }
 
        void meow() {
            System.out.println(name() +" meows");
        }
    }
 
    public static final class Dog extends Pet {
        public Dog(String name) {
            super(name);
        }
 
        void bark() {
            System.out.println(name() +" barks");
        }
    }
}

In this example, the Pet class is declared as sealed, meaning it can only be extended by the classes Cat and Dog, which are defined within the same compilation unit. The Pet class is also declared as abstract to prevent the creation of general Pet instances, allowing only specific instances of Pet.Cat and Pet.Dog.

Sealed Interfaces

Sealed interfaces work similarly to sealed classes, allowing only specified implementations. This is particularly useful in scenarios where you want to define a set of operations or behaviors that can only be implemented by certain classes.

Example: Sealed Interface FXOrder

Here is an example of a sealed interface FXOrder:

public sealed interface FXOrder permits MarketOrder, LimitOrder {
    int units();
    CurrencyPair pair();
    Side side();
    LocalDateTime sentAt();
}
 
public record MarketOrder(int units,
                          CurrencyPair pair,
                          Side side,
                          LocalDateTime sentAt,
                          boolean allOrNothing) implements FXOrder {
 
    // constructors and factories elided
}
 
public record LimitOrder(int units,
                         CurrencyPair pair,
                         Side side,
                         LocalDateTime sentAt,
                         double price,
                         int ttl) implements FXOrder {
 
    // constructors and factories elided
}

In this example, the FXOrder interface is declared as sealed, and it uses the permits keyword to specify that only MarketOrder and LimitOrder can implement it. These implementations are defined as records, which are a special kind of class in Java that provides a compact syntax for declaring data-carrying classes.

Conclusion

The sealed keyword in Java provides a powerful mechanism for controlling class and interface hierarchies. By specifying which classes or interfaces can extend or implement a sealed type, developers can create more maintainable and predictable code structures. This feature is particularly useful in large codebases where the integrity of the type hierarchy is crucial.