Difference between @RequiredArgsConstructor, @AllArgsConstructor, @NoArgsConstructor ?

Difference between @RequiredArgsConstructor, @AllArgsConstructor, @NoArgsConstructor ?

In the Lombok library, @RequiredArgsConstructor, @AllArgsConstructor, and @NoArgsConstructor are annotations used to automatically generate constructors with different levels of arguments for a class. Here’s a brief explanation of each annotation:

@RequiredArgsConstructor

  1. @RequiredArgsConstructor: Generates a constructor with required arguments, which include final fields and fields with constraints, such as @NonNull. Non-final fields without constraints will not be included in the generated constructor.
1
2
3
4
5
6
7
8
9
@RequiredArgsConstructor
public class MyClass {
    private final String requiredField;
    private String nonRequiredField;
}
// Generates the following constructor:
// public MyClass(String requiredField) {
//     this.requiredField = requiredField;
// }

@AllArgsConstructor

  1. @AllArgsConstructor: Generates a constructor with all class fields as arguments, both final and non-final fields.
1
2
3
4
5
6
7
8
9
10
@AllArgsConstructor
public class MyClass {
    private final String field1;
    private String field2;
}
// Generates the following constructor:
// public MyClass(String field1, String field2) {
//     this.field1 = field1;
//     this.field2 = field2;
// }

@NoArgsConstructor

  1. @NoArgsConstructor: Generates a no-argument constructor. If any fields are final, you must provide a default value for those fields in the class definition; otherwise, a compilation error will occur.
1
2
3
4
5
6
7
8
9
@NoArgsConstructor
public class MyClass {
    private final String field1 = "default value";
    private String field2;
}
// Generates the following constructor:
// public MyClass() {
//     // No initialization logic, field1 has a default value, and field2 is null.
// }

These annotations simplify the process of creating constructors with different levels of arguments for a class, helping to reduce boilerplate code. To use these annotations, you need to have Lombok configured in your project.

comments powered by Disqus