Sitemap

Java Sealed Classes

1 min readApr 23, 2024

--

In Java, if we want that no other class can inherit our class then we use the final keyword , but what if we want to restrict the number of classes that can inherit from the given class we use sealed classes.

For Example:

sealed class A permits C,B{

}

public non-sealed class B extends A{

}

public final class C extends A{

}

Above given examples are valid demonstration of a sealed class

Get Kumar Shubham’s stories in your inbox

Join Medium for free to get updates from this writer.

Points to be Noted:

  • We use the keyword permits to mention the classes which could become child of a given sealed class
  • Child class of a sealed class must be a sealed class , a non-sealed class or a final class
  • If any class other than mentioned after permits keyword tries to inherit from a sealed class it will fetch a compilation error.
  • If we don’t use permits with a sealed class it will give us compilation error
  • If child class of a sealed class is also a sealed class then the child class must also use the permits keyword.
  • It was first introduced in java15

--

--