Java Record Getter Example

1. Introduction

In this blog post, we're going to explore the use of getters in Java Records. Records, introduced in Java 16, provide a concise syntax for declaring data-carrying classes. One of the advantages of records is the automatic generation of getters for their fields.

Definition

Java Records generate a public method for each component (field) they declare. These methods, often referred to as getters, allow for the retrieval of the field values. Unlike traditional Java beans, record getters follow the naming pattern of the field name itself rather than the get prefix.

2. Program Steps

1. Define a Java Record with several fields.

2. Create an instance of the record.

3. Use the automatically generated getter methods to access the record's fields.

3. Code Program

// Defining a Record
public record Book(String title, String author, int year) {}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of the record
        Book book = new Book("1984", "George Orwell", 1949);

        // Accessing fields using getters
        System.out.println("Title: " + book.title());
        System.out.println("Author: " + book.author());
        System.out.println("Year: " + book.year());
    }
}

Output:

Title: 1984
Author: George Orwell
Year: 1949

Explanation:

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

2. An instance of the Book record is created using the new keyword and providing values for all fields.

3. The values of the record's fields are accessed using the automatically generated getter methods: title(), author(), and year().

4. The output displays the values of each field, demonstrating the simplicity and effectiveness of getters in Java Records for accessing data.


Comments