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?
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.
return this
simply means "return the reference of the current instance".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With