How do you access the fields of a Java Record?

Java MCQ: How do you access the fields of a Java Record?

a) Using getter methods like getName() and getAge()
b) Using field names directly like name and age
c) Using generated methods with the same name as the fields like name() and age()
d) Using reflection only

Answer:

c) Using generated methods with the same name as the fields like name() and age()

Explanation:

In Java Records, you access the fields using generated methods that have the same names as the fields. These methods are automatically provided by the compiler and are similar to getter methods, but they do not use the traditional “get” prefix.

For example, if you define a record as follows:

public record Person(String name, int age) {}

You can access the name and age fields using the methods name() and age(), respectively:

Person person = new Person("John Doe", 30);
String name = person.name();
int age = person.age();

These methods are automatically generated by the compiler, and they provide read-only access to the fields of the record. Since records are immutable, there are no setter methods or direct access to the fields. This design ensures that the data in a record remains consistent and unmodifiable after the record is created.

This approach simplifies the creation of immutable data classes, making the code more concise and easier to read.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top