Java 16 introduces a new language feature called sealed classes. Sealed classes allow developers to control the inheritance tree more explicitly by specifying which classes can extend them. This feature helps improve encapsulation and maintain better design patterns. In this article, we will explore how sealed classes work and how they can be beneficial in Java development.
Table of Contents
- Introduction to Sealed Classes
- Declaring Sealed Classes
- Sealed Subclasses
- Permitted Subclasses
- Benefits of Sealed Classes
- Conclusion
Introduction to Sealed Classes
In Java, classes can be inherited by other classes, creating a class hierarchy. However, this can sometimes lead to uncontrolled inheritance, where any class can extend a particular class. Sealed classes provide a way to limit which classes can be subclasses of a certain class.
Declaring Sealed Classes
To declare a sealed class, we use the sealed
keyword before the class
keyword. For example:
public sealed class Shape permits Circle, Square, Triangle {
// Class body
}
In the above example, the Shape
class is declared as sealed. The permits
keyword is used to specify the permitted subclasses (Circle
, Square
, and Triangle
in this case).
Sealed Subclasses
A sealed subclass is a class that extends a sealed class. It must be declared with the extends
keyword after the class name. For example:
public final class Circle extends Shape {
// Class body
}
In this example, Circle
is a sealed subclass of the Shape
class. Only the permitted subclasses can extend sealed classes.
Permitted Subclasses
A sealed class specifies the subclasses that are allowed to extend it using the permits
keyword in its declaration. These permitted subclasses must be final or sealed classes themselves. Any attempt to extend a sealed class with a non-permitted subclass will result in a compile-time error.
Benefits of Sealed Classes
Sealed classes offer several advantages in Java development:
- Improved encapsulation: Sealed classes help enforce encapsulation by controlling the inheritance hierarchy and preventing unwanted extensions.
- Better design patterns: With sealed classes, it becomes easier to implement design patterns like the factory pattern, where only limited subclasses are allowed to create instances.
- Enhanced maintainability: Sealed classes provide better control over the class hierarchy, making the code easier to understand, navigate, and maintain.
Conclusion
Sealed classes in Java 16 offer a new way to control and restrict the inheritance hierarchy. With sealed classes, developers can ensure better encapsulation, enforce design patterns, and improve code maintainability. By specifying the permitted subclasses, developers have more control over the extension of classes, leading to cleaner and safer codebases.
References:
#java #java16