Records are a feature introduced in Java 14. They are a new kind of class introduced to reduce boilerplate code for immutable data-carrying objects. Records provide a compact way to declare classes that are transparent holders for shallowly immutable data.
Here's a basic example of how you would define a record in Java.
// No need to explicitly declare fields, constructor, equals, hashCode, or toString
}
In this example, "Person" is a record that consists of two components: "name" and "age". When you define a record, the compiler automatically generates the following:
- Private final fields for each component (e.g., "name" and "age" in this case).
- A public constructor that initializes these fields.
- Getter methods for each component.
- An "equals()" method that compares the contents of two "Person" objects.
- A "hashCode()" method based on the contents of the record.
- A "toString()" method that displays the components' values.
Person modifiedPerson = person.withAge(35);
Nenhum comentário:
Postar um comentário