The Java record class, introduced in Java 14, provides a concise way to declare classes whose main purpose is to hold data. It automatically generates a set of standard methods such as equals()
, hashCode()
, and toString()
. However, in some cases, you may need to define custom methods within a record class to implement additional functionality specific to your application. This article explores how to create custom methods in a Java record class and demonstrates their usage with relevant code examples.
Creating a Java Record Class
Before diving into custom methods, let’s briefly review how to create a Java record class. A record class is declared using the record
keyword, followed by the class name and a list of fields:
public record Person(String name, int age) {
// Record body
}
In this example, we define a record class named Person
with two fields: name
of type String
and age
of type int
. The record class automatically generates the constructor, accessor methods, equals()
, hashCode()
, and toString()
methods based on the defined fields.
Defining Custom Methods in a Record Class
To define custom methods within a Java record class, you follow the same syntax as you would for any regular class. The only difference is that the methods will be part of the record class’s body. Here’s an example that demonstrates the addition of a custom method isAdult()
to the Person
record class:
public record Person(String name, int age) {
public boolean isAdult() {
return age >= 18;
}
}
In this case, the isAdult()
method checks if the person’s age is greater than or equal to 18 and returns true
if they are an adult. By adding this custom method, we can now easily determine whether a Person
object represents an adult or not.
Using Custom Methods in a Record Class
Once you have defined custom methods in your record class, you can use them just like any other method. Here’s an example that demonstrates the usage of the isAdult()
method:
Person john = new Person("John", 25);
boolean isJohnAdult = john.isAdult(); // Returns true
Person jane = new Person("Jane", 16);
boolean isJaneAdult = jane.isAdult(); // Returns false
In this code snippet, we create two Person
objects: john
with an age of 25 and jane
with an age of 16. By calling the isAdult()
method on each object, we determine whether they are adults or not. The result is stored in the respective isJohnAdult
and isJaneAdult
variables.
Overriding Generated Methods in a Java Record Class
In addition to defining custom methods, Java record classes also provide the flexibility to override the generated methods such as equals()
, hashCode()
, and toString()
. This allows you to customize the behavior of these methods based on your specific needs. In this section, we will explore how to override these methods within a Java record class.
Overriding the equals()
Method
The equals()
method in a record class compares the field values of two objects for equality. By default, it performs a field-by-field comparison using the generated equals()
method for each field. However, you can override this behavior by providing your own implementation. Here’s an example:
public record Person(String name, int age) {
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
Person person = (Person) obj;
return age == person.age && name.equals(person.name);
}
}
In this example, we override the equals()
method to compare both the name
and age
fields of two Person
objects. The implementation checks if the objects are the same reference, have the same class, and then compares the field values for equality.
Overriding the hashCode()
Method
The hashCode()
method generates a hash code for a record object based on its field values. By default, it uses the generated hashCode()
method for each field and combines them to produce the final hash code. However, you can override this method to provide your own hash code generation logic. Here’s an example:
public record Person(String name, int age) {
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
In this example, we override the hashCode()
method to generate a hash code based on the name
and age
fields using the Objects.hash()
method. This ensures that two Person
objects with the same field values produce the same hash code.
Overriding the toString()
Method
The toString()
method in a record class returns a string representation of the object. By default, it generates a string that includes the class name and the values of all the fields. However, you can customize this behavior by overriding the toString()
method. Here’s an example:
public record Person(String name, int age) {
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
In this example, we override the toString()
method to provide a customized string representation for the Person
object. The implementation constructs a string that includes the field names and values, making it easier to understand the contents of the object.
Conclusion
Java record classes not only generate useful methods automatically but also allow you to define custom methods and override the generated methods. This article covered the process of overriding the equals()
, hashCode()
, and toString()
methods in a Java record class, providing examples and explanations for each case. By leveraging these capabilities, you can tailor the behavior of your record classes to better suit your application’s requirements.