Can you customize the default behavior of the canonical constructor in Java Records?

Java MCQ: Can you customize the default behavior of the canonical constructor in Java Records?

a) No, the canonical constructor cannot be customized
b) Yes, by defining a compact constructor
c) Yes, by overriding the constructor method
d) Yes, but only for records with a single field

Answer:

b) Yes, by defining a compact constructor

Explanation:

In Java Records, you can customize the default behavior of the canonical constructor by defining a compact constructor. A compact constructor allows you to add additional logic, such as validation or computation, while still benefiting from the concise syntax provided by records.

Here’s an example of a record with a compact constructor:

public record Rectangle(int length, int width) {
    public Rectangle {
        if (length <= 0 || width <= 0) {
            throw new IllegalArgumentException("Length and width must be positive");
        }
    }
}

In this example, the compact constructor checks that the length and width fields are positive. If they are not, an IllegalArgumentException is thrown. The compact constructor does not need to explicitly declare the parameters (int length, int width) since they are already declared in the record header. The parameters are implicitly available within the constructor body.

Using a compact constructor allows you to maintain the simplicity of records while still customizing their behavior to meet specific requirements. This feature is particularly useful when you need to enforce constraints or perform additional initialization logic.

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