Search code examples
javarecordsealedsealed-class

When are sealed classes and records used together in Java?


JEP on sealed classes says :

Sealed classes do not depend on records (JEP 384) or pattern matching (JEP 375), but they work well with both.

What does it mean "work well"? Are there any recommendations to use the combination in some specific cases?


Solution

  • Records cannot extend another class. Thus, 'sealed classes' + 'records' don't work at all.

    Records can, however, implement interfaces, and the 'sealed classes' proposal is shorthand for the full name of this JEP which is 'sealed classes and interfaces'.

    sealed interfaces + records works. I don't think applying the term 'well' is particularly applicable here. It doesn't not work, I guess.

    You can have your record definition implement a sealed interface. If your sealed interface contains any method definitions which match the methods that a record would generate automatically, then things just work out. For example:

    public sealed interface Person permits Student, Teacher {
        String name();
    }
    
    public record Student(String name, int id) implements Person {}
    
    public record Teacher(String name) implements Person {}
    

    would work. The record feature makes the name() method exist, thus allowing Student and Teacher to fulfill the Person interface.

    The two features seem entirely orthogonal. They don't get in each other's way nor does one require or at least (significantly) benefit from the existence of the other.