Customizing Java Records
If you have not read my article on Java records and do not know about this topic, please read my blog titled "Java Keywords Addendum: The Java Record" first and then come back to this one.
If I were to run this code like this
It would produce an output like this
Now suppose I want to display the contents of this object in a different way than the default implementation hidden from me by the
Printing out this object will now look like this:
You can also add your own custom code. Suppose you create a Java record to represent a geometric shape and wish to add methods to do calculations like perimeter and area. You can do that as well.
And that is in a nutshell how you customize Java records. I hope you found this information useful. See you next time! If you haven't read it already, check out my last blog on Java records: Implementing Interfaces with Java Records.
What is a customization of a record?
A customization of a record is simply the addition of code inside the body of the class. Before proceeding further, let's recap important aspects of a Java Record:- Java records are immutable
- Because of item 1 above, you cannot add new fields unless defined in the record constructor
- Java records already override:
Object#equals(Object)
andObject#hashCode()
, and then overrideObject#toString()
Object#toString()
method, you could do so. Let's look at our first customization example. Using the example from my previous blog,
public record Student(String name, int id) {}
Student student = new Student("Hector", 1);
System.out.println(student);
Student[name=Hector, id=1]
record
implmentation. I can simply override the method inside the body of the record.
public record Student(String name, int id) {
@Override
public String toString() {
StringBuilder sbuff = new StringBuilder();
sbuff.append("**** START OF RECORD ****");
sbuff.append("\n");
sbuff.append("Student's name: ");
sbuff.append(name);
sbuff.append("\n");
sbuff.append("Student's ID: ");
sbuff.append(id);
sbuff.append("\n");
sbuff.append("***** END OF RECORD *****");
return sbuff.toString();
}
}
**** START OF RECORD ****
Student's name: Hector
Student's ID: 1
***** END OF RECORD *****
public record Rectangle(double width, double height) {
public double area() {
return width * height;
}
public double perimeter() {
return 2 * (width + height);
}
}
Comments
Post a Comment