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.

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:
  1. Java records are immutable
  2. Because of item 1 above, you cannot add new fields unless defined in the record constructor
  3. Java records already override: Object#equals(Object) and Object#hashCode(), and then override Object#toString()
You could redefine overridden methods as part of your customization if you would like. For example, if you want a fancier implementation of the 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) {}
		
    
If I were to run this code like this
    	
Student student = new Student("Hector", 1);
System.out.println(student);
        
    
It would produce an output like this
    	
Student[name=Hector, id=1]
		
    
Now suppose I want to display the contents of this object in a different way than the default implementation hidden from me by the 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();
    }
}
        
    
Printing out this object will now look like this:
    	
**** START OF RECORD ****
Student's name: Hector
Student's ID: 1
***** END OF RECORD *****
        
    
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.
    	
public record Rectangle(double width, double height) {

    public double area() {
        return width * height;
    }

    public double perimeter() {
        return 2 * (width + height);
    }
}
        
    
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.

Comments

Popular posts from this blog

Implementing Interfaces with Java Records

Exception Handling: File CRUD Operations Example