top of page
Nilay Patel

Java 17 Sealed class

Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them. One of the primary purposes of inheritance is code reuse: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug) them yourself.

By sealing a class, you can specify which classes are permitted to extend it and prevent any other arbitrary class from doing so.


Declaring Sealed Classes


To seal a class, add the sealed modifier to its declaration. Then, after any extends and implements clauses, add the permits clause. This clause specifies the classes that may extend the sealed class.


public sealed class Vehicle permits Toyota, Honda, Hyndai {}


Define the following three permitted subclasses in the same module or in the same package as the sealed class:


public final class Toyota extends Vehicle {

double engineNo;

}


public sealed class Honda extends Vehicle {

double engineNo;

}


public non-sealed class Hyundai extends Vehicle {

double engineNo;

}


Constraints on Permitted Subclasses


Permitted subclasses have the following constraints:

  • They must be accessible by the sealed class at compile time. For example, to compile Vehicle.java, the compiler must be able to access all of the permitted classes of Vehicle: Toyota.java, Honda.java, and Hyndai.java.

  • They must directly extend the sealed class.

  • They must have exactly one of the following modifiers to describe how it continues the sealing initiated by its superclass:

    • final: Cannot be extended further

    • sealed: Can only be extended by its permitted subclasses

    • non-sealed: Can be extended by unknown subclasses; a sealed class cannot prevent its permitted subclasses from doing this

For example, the permitted subclasses of Vehicle demonstrate each of these three modifiers: Toyota is final while Honda is sealed and Hyundai is non-sealed.

  • They must be in the same module as the sealed class (if the sealed class is in a named module) or in the same package (if the sealed class is in the unnamed module, as in the Vehicle.java example).

16 views0 comments

Recent Posts

See All

Battle of the Backends: Java vs Node.js

Comparing Java and Node.js involves contrasting two distinct platforms commonly used in backend development. Here’s a breakdown of their...

Comments


bottom of page