Junior — Middle
What is the main difference between @AllArgsConstructor and @RequiredArgsConstructor in Lombok?
sobes.tech AI
Answer from AI
Lombok annotations @AllArgsConstructor and @RequiredArgsConstructor automatically generate constructors for a class, but with different sets of parameters:
-
@AllArgsConstructorcreates a constructor with all class fields (including initialized and uninitialized ones). -
@RequiredArgsConstructorcreates a constructor only with the required fields — those declared asfinalor annotated with@NonNull.
Example:
@AllArgsConstructor
@RequiredArgsConstructor
public class User {
private final String name;
private int age;
}
@AllArgsConstructorwill generate a constructorUser(String name, int age).@RequiredArgsConstructorwill generate a constructorUser(String name).
Thus, @RequiredArgsConstructor is useful when you want to ensure initialization of only the required fields, while @AllArgsConstructor is used when a constructor for all fields is needed.