Sealed Class in Java

Profile picture for user arilio666

In Java, a sealed class is a class that restricts which other classes or interfaces can extend or implement it. It defines a limited set of subclasses or implementing classes, which provides better control over class hierarchy and encapsulation.
This is introduced in Java 15 as a preview feature that provides fine control over the inheritance.

  • A sealed class is established using the keyword sealed.
  • Subtype class can be controlled using the keyword permit.
  • A class extending a sealed class should be either sealed, non-sealed, or final.

Here's how we can use the sealed class:

public sealed class Animal permits Dog, Cat {
}
final class Dog extends Animal {
}
final class Cat extends Animal {
}
  • In the above example, Animal is a sealed class that permits only Dog and Cat to extend it. 
  • The Dog and Cat classes are marked as final to prevent further extension.
non-sealed class Fish extends Animal {
}
  • You can also use the non-sealed modifier to allow any class or interface to extend or implement a sealed class. 
  • The Fish class can extend the Animal sealed class because it is marked as non-sealed.

Conclusion:

Using sealed classes in Java can provide better control and encapsulation over class hierarchies and help prevent unintended subclassing or implementation.

Tags