javaclasssealed-classjava-17java-sealed-type

What are sealed classes in Java 17?


Today, I updated my Java version from 16 to 17, and I found that sealed classes is a new feature in it. I think it can be declared like this:

public sealed class Main permits AClass, AnotherClass {
}

But, what is the use of sealed classes in Java?

I also knew that it was a preview feature in JDK 15.


Solution

  • You can follow this link for examples.

    In short, sealed classes gives you the control of which models, classes etc. that can implement or extend that class/interface.

    Example from the link:

    public sealed interface Service permits Car, Truck {
    
        int getMaxServiceIntervalInMonths();
    
        default int getMaxDistanceBetweenServicesInKilometers() {
            return 100000;
        }
    }
    

    This interface only permits Car and Truck to implement it.