What is the purpose of a sealed or final class, and when would you prevent a class from being extended?

Last updated 5 July 2026

  • A sealed/final class prevents inheritance, so no subclass can alter its behavior or break invariants (e.g. immutable String).

  • Use it when a class wasn't designed for extension, avoiding fragile-base-class problems. It also documents intent and enables devirtualization optimizations.

  • In Kotlin and modern Java, sealed instead restricts subclasses to a fixed known set, enabling exhaustive pattern matching.

  • https://www.baeldung.com/java-final
  • https://dev.to/hamidmolareza/-sealed-preventing-inheritance-in-c-3cl3
  • https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/sealing
  • https://medium.com/c-sharp-programming/sealed-classes-in-c-b9cb0ba8f9ad
  • https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/sealed
All Object-Oriented Programming interview questions