177. Combining sealed classes and records
As you know from Chapter 4, Java records are final
classes that cannot be extended and cannot extend other classes. This means that records and sealed
classes/interfaces can team up to obtain a closed hierarchy.
For instance, in the following figure, we can identify the classes that can be good candidates to become Java records in the Fuel model:
Figure 8.6: Identify classes that can become Java records
As you can see, we have four classes that can become Java records: Coke
, Charcoal
, Hydrogen
, and Propane
. Technically speaking, these classes can be Java records since they are final
classes and don’t extend other classes:
public record Coke() implements SolidFuel {}
public record Charcoal() implements SolidFuel {}
public record Hydrogen() implements NaturalGas {}
public record Propane() implements GaseousFuel {}
Of course, the technical aspect is important but it is not enough. In other words, you don’...