Other Aspects of Record Classes
Some other aspects of record classes are mentioned below, and are covered in detail elsewhere in the book.
Implementing Interfaces
Records can implement interfaces, which is no different from a normal class implementing interfaces. As a record class is implicitly final, it cannot extend other classes. The CD record class below implements the Serializable interface and the Comparable<CD> interface. Example 20.6, p. 1263, uses the CD record class to demonstrate record serialization.
public record CD(String artist, String title, int noOfTracks, // (1)
Year year, Genre genre) implements Serializable and Comparable<CD> {
@Override public int compareTo(CD other) { /* See Example 16.1, p. 883. */ }
public enum Genre implements Serializable {POP, JAZZ, OTHER}
}
The CD record class in Example 16.1, p. 883, implements the Comparable<CD> interface so that CD records can be compared.
Record Serialization
Example 20.6, p. 1263, demonstrates serializing records to external storage. It is important to note that serialization of records cannot be customized, as with objects of normal classes, and that a record is always deserialized using the canonical constructor.
Generic Record Classes
Generic record classes can be delcared, analogous to generic classes (Chapter 11, p. 563). The generic record class Container below has one type parameter (T):
record Container<T>(T item) { /* Empty body */ }
We can create records by parameterizing the generic record class:
Container<String> p0 = new Container<>(“Hi”);
Container<Integer> p1 = new Container<>(Integer.valueOf(10));
Nested Record Classes
Record classes can be declared as nested record classes—in particular, as static member types and as static local types. For details on nested record classes, see Chapter 9, p. 489.
Direct Permitted Subtypes of Sealed Interfaces
A record class is only allowed in the permits clause of a sealed interface, if it implements the sealed interface. As a record class is implicitly final, it also fulfills the second criterion for a permitted direct subtype (p. 311).
Finally, it is worth noting that records in Java are designed so that the record state solely defines the representation of the record. Record classes require less effort to implement than normal classes and have an efficient memory footprint and runtime performance. Also, their immutability provides thread safety in concurrent applications.
Leave a Reply