What are sealed classes in Java 17

user16411474 picture user16411474 · Sep 17, 2021 · Viewed 7.5k times · Source

Today I updated my java version from 16 to 17 and I found that sealed class is a new feature in it. I think it can be declared like this -

public sealed class Main{

}

But what is the use of sealed classes in java?

I also knew that it was a preview feature in jdk-15

Answer

JDTheOne picture JDTheOne · Sep 17, 2021

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.