Ask Your Question
4

How can a custom constructor be created for a Java Record?

asked 2023-06-08 07:01:48 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-08 07:02:02 +0000

lalupa gravatar image

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:

  1. Define the class and its properties using the "record" keyword. For example:
public record Person(String name, int age) {
    // class logic
}
  1. Define the custom constructor with the desired parameters. For example:
public Person(String name, int age, String email) {
    this.name = name;
    this.age = age;
    this.email = email;
}
  1. Inside the constructor, set the values of the record's properties using the "this" keyword.

  2. 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;
}
  1. Save the file and use the custom constructor to create objects that match the defined parameters. For example, to create a Person object with the name "John", age 30, and email "john@gmail.com":
Person john = new Person("John", 30, "john@gmail.com");
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-08 07:01:48 +0000

Seen: 14 times

Last updated: Jun 08 '23