Java 17 introduced sealed classes and interfaces, which allow developers to explicitly define the permitted direct subtypes. This mechanism provides a way to restrict the inheritance hierarchy, ensuring that only specified classes can extend or implement a sealed type. For example, a sealed interface can declare specific record types as its only allowed implementations.
A key benefit of sealed types is their integration with switch expressions, enabling exhaustive pattern matching. The compiler can verify that all possible subtypes of a sealed type are handled in a switch expression. If all cases are covered, a default clause is not required. Forgetting a case without a default results in a compile-time error, ensuring comprehensive handling of all defined subtypes.
While exhaustiveness checking is beneficial for code correctness, it introduces a new consideration for API evolution. Adding a new subtype to an existing sealed class or interface constitutes a breaking change. Consumers of the API that use switch expressions on the sealed type will fail to compile if they are not updated to handle the new subtype. This implies that such changes would necessitate a major version bump under semantic versioning.
The exhaustiveness check primarily occurs at compile-time. However, if a consumer application is not recompiled after a sealed type's definition changes (e.g., a new subtype is added), runtime issues can arise. If the consumer's compiled code encounters an instance of the newly added subtype that it was not compiled to handle, it could lead to unexpected runtime behavior or errors, as the switch expression would not have a matching case.
✨ This summary was generated by AI from the outlets' reporting listed below. It is not independently verified and may contain errors — check the original sources. How BrevFeed works →
One email each morning: the day's tech stories, clustered across outlets and summarized. No account needed.
One email a day. Unsubscribe in one click, any time.
Spend a few minutes, get the whole day. Every topic's top stories in one hands-free rundown — listen, watch, or read the transcript.
▶ Play today's briefNew every morning, and the back catalogue is archived by date.
Java 17 introduced sealed classes, enabling explicit listing of allowed subtypes for interfaces or base classes and providing compile-time exhaustiveness checking for switch expressions. This feature eliminates the need for default clauses in switches if all subtypes are covered, but adding new subtypes to a sealed class becomes a breaking change for consumers that are not recompiled.