Java Record Custom Methods

1. Introduction

In this blog post, we'll explore how to add custom methods to Java Records. While records in Java are primarily intended for holding data, they can also include additional functionality through custom methods, enhancing their versatility.

Definition

A Java Record is an immutable data holder. It automatically generates getters, equals(), hashCode(), and toString() methods. However, developers can extend its functionality by adding custom methods to records, providing additional behaviors beyond basic data access.

2. Program Steps

1. Define a Java Record with a few fields.

2. Add a custom method to the record.

3. Create an instance of the record and use the custom method.

3. Code Program

// Record with a custom method
public record Book(String title, String author, int year) {

    // Custom method to get a formatted description
    public String getFormattedDescription() {
        return title + " by " + author + " (" + year + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        Book book = new Book("1984", "George Orwell", 1949);

        // Using the custom method
        System.out.println(book.getFormattedDescription());
    }
}

Output:

1984 by George Orwell (1949)

Explanation:

1. The Book record is defined with title, author, and year.

2. A custom method getFormattedDescription is added to the Book record. This method combines the record's fields into a formatted string.

3. In the main method, an instance of Book is created.

4. The getFormattedDescription method is called on the Book instance, which prints a formatted description of the book.

5. This demonstrates how custom methods in Java Records can provide additional functionality beyond the default getters and overridden methods.


Comments