A Java Record is a compact way to declare a class that is primarily used to store data. It includes a default constructor that can be used to create objects, but it is also possible to create a custom constructor to suit specific needs.
To create a custom constructor for a Java Record, the following steps can be followed:
public record Person(String name, int age) {
// class logic
}
public Person(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
Inside the constructor, set the values of the record's properties using the "this" keyword.
Use the "super" keyword to call the default constructor of the Java record class. For example, to include the default "record" constructor, the custom constructor should look like this:
public Person(String name, int age, String email) {
super(name, age);
this.email = email;
}
Person john = new Person("John", 30, "john@gmail.com");
Asked: 2023-06-08 07:01:48 +0000
Seen: 14 times
Last updated: Jun 08 '23