Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Lombok, what is the difference between @AllArgsConstructor and @RequiredArgsConstructor?

Tags:

java

lombok

Lombok offers a variety of annotations for java constructors, including but not limited to @AllArgsConstructor and @RequiredArgsConstructor. What is the difference between these two and when do you use one over the other? I found this documentation but the verbiage is a little convoluted and I'm having trouble following the basic differences between the two.

like image 577
Matt C. Avatar asked Aug 30 '25 14:08

Matt C.


1 Answers

In short, use @AllArgsConstructor to generate a constructor for all of your class's fields and use @RequiredArgsConstructor to generate a constructor for all class's fields that are marked as final.

From the documentation,

@AllArgsConstructor generates a constructor with 1 parameter for each field in your class.

@RequiredArgsConstructor generates a constructor with 1 parameter for each field that requires special handling. All non-initialized final fields get a parameter, as well as any fields that are marked as @NonNull that aren't initialized where they are declared.

like image 162
Matt C. Avatar answered Sep 02 '25 17:09

Matt C.