Reputation: 139
I'm developing a simple java project to help me master the language and was researching on method chaining when I came across the return this
statement. I'm not quite sure of its use cases apart from method chaining and what it means exactly to return this
. Its documentation was obviously not written for newbies. Could someone help make it clearer?
Upvotes: 8
Views: 7795
Reputation: 425208
return this;
returns the instance itself from the method.
Returning the instance is usually (but not always) used when implementing a fluent interface, which allows code to look like this:
myObj.method1().method2().method3();
This in turn is very commonly used (but not required) when implementing the builder pattern.
Upvotes: 15
Reputation: 56463
return this
simply means "return the reference of the current instance".
Upvotes: 1