Java Record Default Constructor

1. Introduction

In this blog post, we will explore the concept of the default constructor in Java Records. Introduced in Java 16, records are a way to simplify the creation of immutable data carrier classes. Understanding the default constructor in records is crucial for effectively using them in Java.

Definition

Java Records automatically provide a canonical constructor, which is the default constructor for records. This constructor initializes the record's fields with the values passed to it. It's important to note that unlike traditional classes, you cannot declare a no-argument constructor in records.

2. Program Steps

1. Define a Java Record.

2. Create an instance of the record using the canonical constructor.

3. Access the record's fields.

3. Code Program

// Defining a Record
public record Employee(String name, int age) {}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of the record using the canonical constructor
        Employee employee = new Employee("Alice", 30);

        // Accessing fields
        System.out.println("Employee Name: " + employee.name());
        System.out.println("Employee Age: " + employee.age());
    }
}

Output:

Employee Name: Alice
Employee Age: 30

Explanation:

1. The Employee record is defined with two components: name and age.

2. An instance of the Employee record is created using the canonical constructor, which is the default constructor provided by Java for records.

3. The name() and age() methods, which are automatically generated by Java for the record's components, are used to access the Employee's name and age.

4. The output demonstrates the creation of a record instance using its canonical constructor and the retrieval of its field values.


Comments