90. Adding more artifacts in a record
So far, we know how to add an explicit canonical/compact constructor into a Java record. What else can we add? Well, for example, we can add instance methods as in any typical class. In the following code, we add an instance method that returns the weight
converted from grams to kilograms:
public record MelonRecord(String type, float weight) {
public float weightToKg() {
return weight / 1_000;
}
}
You can call weightToKg()
exactly as you call any other instance method of your classes:
MelonRecord melon = new MelonRecord("Cantaloupe", 2600);
// 2600.0 g = 2.6 Kg
System.out.println(melon.weight() + " g = "
+ melon.weightToKg() + " Kg");
Besides instance methods, we can add static
fields and methods as well. Check out this code:
public record MelonRecord(String type, float weight) {
private static final String DEFAULT_MELON_TYPE = "Crenshaw";
private static final float...