85. Adding more artifacts in a record
So far, we know how to add in a Java record an explicit canonical/compact constructor. What else we can 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 DEFAULT_MELON_WEIGHT = 1000;
public static MelonRecord getDefaultMelon() {
return new MelonRecord(
DEFAULT_MELON_TYPE, DEFAULT_MELON_WEIGHT);
}
}
Calling getDefaultMelon() is done as usual via class name:
MelonRecord defaultMelon = MelonRecord.getDefaultMelon();
Adding nested classes is also possible. For example, here we add a static nested class:
public record MelonRecord(String type, float weight) {
public static class Slicer {
public void slice(MelonRecord mr, int n) {
start();
System.out.println(“Slicing a ” + mr.type() + ” of “
+ mr.weightToKg() + ” kg in ” + n + ” slices …”);
stop();
}
private static void start() {
System.out.println(“Start slicer …”);
}
private static void stop() {
System.out.println(“Stop slicer …”);
}
}
}
And, calling Slicer can be done as usual:
MelonRecord.Slicer slicer= new MelonRecord.Slicer();
slicer.slice(melon, 10);
slicer.slice(defaultMelon, 14);
But, even if it is allowed to add all these artifacts in a Java record, I strongly suggest you think twice before doing this. The main reason is that Java records should be about data and only data, so is kind of weird to pollute a record with artifacts that involves additional behavior. If you hit such a scenario then probably you need a Java class, not a Java record.In the next problem, we will see what we cannot add to a Java record.