Sealed Classes and Interfaces in Java.
1. OverviewThe release of Java SE 15 introduces sealed classes ( JEP 360 ) as a preview feature. This feature is about enabling more fine-grained inheritance control in Java. Sealing allows classes and interfaces to define their permitted subtypes. In other words, a class or an interface can now define which classes can implement or extend it. It is a useful feature for domain modeling and increasing the security of libraries. 2. MotivationA class hierarchy enables us to reuse code via inheritance. However, the class hierarchy can also have other purposes. Code reuse is great but is not always our primary goal. 2.1. Modeling PossibilitiesAn alternative purpose of a class hierarchy can be to model various possibilities that exist in a domain. As an example, imagine a business domain that only works with cars and trucks, not motorcycles. When creating the Vehicle abstract class in Java, we should be able to allow only Car and Truck ...