Records have been in Java since version 16, but what are they and what can you use them for?
Records can be thought of as a replacement for simple data-holding POJOs.
These holders usually have one or more of the following properties:
- They are defined solely by the data they hold
- They have an
equals()
andhashCode()
method based solely on their data - Their fields are private and final, and they define a getter method for them
- They are written to and read from another format, like JSON or the database
Here is an example of such a POJO:
final class Customer {
private final UUID id;
private final String name;
public Customer(UUID id, String name) {
this.id = id;
this.name = name;
}
public UUID getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Customer[id=" + id + ", name=" + name + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Customer customer = (Customer) o;
return id.equals(customer.id) && name.equals(customer.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
Now let's see the equivalent record implementation:
record Customer(String id, String name) {}
Need we say more? You can now stop reading and start using records everywhere,
or you can continue on to Part 2: how you use Java Records.
Top comments (0)