Welcome to CodeYourCraft's Java 17 Sealed Classes tutorial! Today, we're going to dive into sealed classes, a new feature introduced in Java 17 that enhances type safety and readability in your code.
Before we start, let's quickly recap what we already know about classes and interfaces.
Now, let's get started with sealed classes!
Sealed classes are a way to limit the set of implementations for an enumeration-like class. They help in enhancing type safety, as you can control which classes can extend the sealed class. This can be particularly useful when working with enums with associated data or strategies.
A sealed class is created using the sealed keyword followed by the class name. Within the sealed class, you can define permitted subclasses using the permits keyword.
Here's an example of a sealed class representing different types of shapes:
sealed class Shape permits Circle, Rectangle, Square {
// Common properties and methods for all shapes
}
record Circle(double radius) implements Shape {
// Specific properties and methods for circle
}
record Rectangle(double width, double height) implements Shape {
// Specific properties and methods for rectangle
}
record Square(double side) implements Shape {
// Specific properties and methods for square
}In this example, we have a sealed class Shape that allows only three classes (Circle, Rectangle, and Square) to extend it.
Let's consider a practical example where we want to create a system for validating user input. We have a sealed class ValidationStrategy with subclasses for different validation strategies.
sealed class ValidationStrategy permits EmailValidation, PasswordValidation, CardNumberValidation {
// Common properties and methods for all validation strategies
}
record EmailValidation(String email) implements ValidationStrategy {
// Specific validation for email input
}
record PasswordValidation(String password) implements ValidationStrategy {
// Specific validation for password input
}
record CardNumberValidation(String cardNumber) implements ValidationStrategy {
// Specific validation for card number input
}In this example, we have a sealed class ValidationStrategy with three subclasses for email, password, and card number validation. By using sealed classes, we can ensure that only the intended validation strategies are used, improving type safety and readability.
What is the main purpose of a sealed class in Java?
That's all for today's Java 17 Sealed Classes tutorial! In the next lesson, we'll dive deeper into using sealed classes in real-world projects. Happy coding! 🚀