1

I want to know why setter methods has return this; in it. What does it mean?

new Person().setName("alex");
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • [Method chaining - why is it a good practice, or not?](https://stackoverflow.com/q/1103985/1371329) – jaco0646 Aug 11 '22 at 22:37

2 Answers2

1

That's called a fluent interface.

The Builder pattern doesn't necessarily dictate that it has to be fluent, but that's often how it's implemented. It allows for users of the Builder to string together multiple calls (ie, "fluent"):

Persoon al = Person.builder()
            .setFirstName("Albert")
            .setLastName("Einstein")
            .setOccupation("Genius")
            .setGender(Gender.Male)
            .build();
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
E-Riz
  • 31,431
  • 9
  • 97
  • 134
0

As already answered, it's not necessary, but it is the convention. And by using it, you can take advantage of the method chaining (Note that method chaining eliminates an extra variable for each intermediate step). You can see: Why is the usage of builder pattern highly encouraged instead of a straight forward implementation of fluent API in Java? and Using fluent interface with builder pattern