Java Sealed Classes

Restrict which other classes or interfaces may extend or implement them.

Introduced in Java 17, sealed classes provide finer-grained control over inheritance than final by explicitly specifying subclasses via the permits keyword.

Key Takeaways: Java Sealed Classes

Mastering Java Sealed Classes helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java Sealed Classes Code Example

Java
public sealed interface Shape permits Circle, Square {}

final class Circle implements Shape {}
final class Square implements Shape {}

public class Main {
    public static void main(String[] args) {
        Shape s = new Circle();
        System.out.println("Sealed shape instantiated: " + s.getClass().getSimpleName());
    }
}
Output
Sealed shape instantiated: Circle
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services