88. Declaring a Java record
Before diving into Java records, let’s think a little bit about how we commonly hold data within a Java application. You’re right … we define simple classes containing the needed instance fields populated with our data via the constructors of these classes. We also expose some specific getters, and the popular equals()
, hashCode()
, and toString()
methods. Further, we create instances of these classes that wrap our precious data and we pass them around to solve our tasks all over our application. For instance, the following class carries data about melons like the melon types and their weights:
public class Melon {
private final String type;
private final float weight;
public Melon(String type, float weight) {
this.type = type;
this.weight = weight;
}
public String getType() {
return type;
}
public float getWeight() {
return weight;
}
// hashCode(), equals(), and to String()
}
You should be...