Member-only story

Understanding Sealed Classes in Java: A Simple Guide

Naveen Metta

--

source: coderstea.in

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:

  1. Use the sealed keyword
  2. 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…

--

--

Naveen Metta
Naveen Metta

Written by Naveen Metta

I'm a Full Stack Developer with 3+ years of experience. feel free to reach out for any help : mettanaveen701@gmail.com

No responses yet