What are Sealed Classes in Java and interfaces in JDK 17, and how to use them?
In this article, we will delve into the new features introduced in Java 17. It’s high time to consider upgrading from Java 8 to Java 17, as Java will
Why do we need a sealed class?
This feature in Java aims to enhance inheritance control with greater precision. Sealing empowers classes and interfaces to specify their allowed subtypes, granting them the authority to determine which classes can implement or extend them. This valuable addition proves beneficial for domain modeling and bolstering library security.
A class hierarchy can serve another purpose, which involves representing various possibilities within a specific domain.
For instance, consider a business domain exclusively dealing with cars and trucks, excluding motorcycles. To achieve this, when designing the abstract class “Vehicle” in Java, we aim to restrict its extension solely to the “Car” and “Truck” classes. This constraint ensures the proper utilization of the “Vehicle” abstract class within our domain, preventing unintended subclasses.
In this scenario, the primary focus lies in maintaining code clarity while handling known subclasses, rather than guarding against all potential unknown subclasses.
Before Java version 15, which introduced sealed classes as a preview, code reuse was presumed to be an overarching objective, allowing any class to be extended by an unrestricted number of subclasses.
The primary goal of developing a superclass alongside its subclasses is to provide clear documentation for its intended usage without imposing limitations on its subclasses. Moreover, having restricted subclasses should not hinder the accessibility of the superclass.
Sealed classes were introduced with the principal aim of allowing a superclass to maintain widespread accessibility while controlling its extensibility. This way, developers can strike a balance between openness and restriction in class hierarchies.
Sealed Interface:
To create a sealed interface, we simply apply the “sealed” modifier to its declaration. The subsequent “permits” clause allows us to specify the classes that are authorized to implement this sealed interface:
public sealed interface Service permits Car, Truck {
int getMaxServiceIntervalInMonths();
default int getMaxDistanceBetweenServicesInKilometers() {
return 100000;
}
}
Sealed Classes:
Just like interfaces, classes can be sealed using the “sealed” modifier. To ensure correct syntax, the “permits” clause must be placed after any “extends” or “implements” clauses:
public abstract sealed class Vehicle permits Car, Truck {
protected final String registrationNumber;
public Vehicle(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}
A permitted subclass must define a modifier. It may be declared final to prevent any further extensions:
public final class Truck extends Vehicle implements Service {
private final int loadCapacity;
public Truck(int loadCapacity, String registrationNumber) {
super(registrationNumber);
this.loadCapacity = loadCapacity;
}
public int getLoadCapacity() {
return loadCapacity;
}
@Override
public int getMaxServiceIntervalInMonths() {
return 18;
}
}
A permitted subclass may also be declared sealed. However, if we declare it non-sealed, then it is open for extension:
public final class Car extends Vehicle implements Service {
private final int numberOfSeats;
public Car(int numberOfSeats, String registrationNumber) {
super(registrationNumber);
this.numberOfSeats = numberOfSeats;
}
public int getNumberOfSeats() {
return numberOfSeats;
}
@Override
public int getMaxServiceIntervalInMonths() {
return 12;
}
}
Are you preparing for a job interview as a Java developer? Congratulations! To help you succeed in your interview, we have compiled a comprehensive list of top Java developer interview questions. Whether you’re a beginner or an experienced developer, these questions cover a wide range of Java concepts, coding techniques, and best practices. From core Java to advanced topics like multithreading, exception handling, and design patterns, this article will equip you with the knowledge and confidence to showcase your Java expertise. Dive in and prepare yourself to excel in your next Java developer interview!
Guide To Clear Java Developer Interview
Grokking the Spring Boot Interview
Thanks for Reading follow me for more Java Developer Content.