Previewed feature in java 15 & Java 16. Sealed Classes standardized in Java 17.
General Q & A
What are Sealed Classes ?
Sealed classes and interfaces restrict which other classes & interfaces may extend or implement.
Why would you want to restrict the extensibility of class?
Increases thread safety.
No derived classes can be used to break the API of the parent class.
Protect the internal state of classes.
Mark the class with the sealed to restrict access sub-classes. Followed by the permits keyword to allowed list of sub-classes.
Permitted sub-class needs to have the extended keyword.
Code example can be found here.
This is a good strategy to protect your classes from unwanted extensions.
One thought on “Java 17 – Sealed Classes”
Pingback: Java Versions & Features - Spaghetti Code Jungle