Java MCQ: How do you access the fields of a Java Record?
Answer:
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