What is the purpose of a sealed or final class, and when would you prevent a class from being extended?
Last updated
A
sealed/finalclass prevents inheritance, so no subclass can alter its behavior or break invariants (e.g. immutableString).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,
sealedinstead 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