Appreciating records
Records are a special type of class, and are considered “data carriers”. They help us avoid typing in copious amounts of boilerplate code. Records are specified using a record declaration where you list the components of the record. Implicitly generated in the background are a canonical constructor; toString
, equals
, and hashCode
methods and public
accessor methods for each of the components specified. The accessor methods take on the same names as the components themselves (as opposed to the more traditional get
methods). Records are best explained by contrasting them to regular classes. Figure 8.29 presents a normal class with a lot of boilerplate code:
Figure 8.29 - A class with a lot of boilerplate code
The Person
class in the preceding figure is customized somewhat to map to a record more easily. For example, the class itself is final
(line 5) and the instance variables, namely name
and age
(lines 6-7), are also...