Member-only story
Understanding Sealed Classes in Java: A Simple Guide
What are Sealed Classes?
Sealed classes are a feature that came to Java in version 17. Think of them as a way to control which classes can inherit from a parent class. It’s like having a VIP list — only the classes you specifically allow can join the party!
Why Do We Need Sealed Classes?
Let’s understand this with a simple example from real life. Imagine you’re making a game with different types of players:
- Regular Player
- Premium Player
- Admin Player
You want to make sure no one can create new types of players that you haven’t planned for. This is exactly what sealed classes help you do!
How to Create Sealed Classes
Creating a sealed class is pretty straightforward. You just need to:
- Use the
sealed
keyword - List all the allowed classes using
permits
Here’s a simple example:
public sealed class Player permits RegularPlayer, PremiumPlayer, AdminPlayer {
private String name;
public Player(String name) {
this.name = name;
}
public String getName() {
return name…