Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and how to Use "return this" in Java

Tags:

java

return

this

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?

like image 520
amolocaleb Avatar asked Jun 01 '18 16:06

amolocaleb


2 Answers

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.

like image 154
Bohemian Avatar answered Oct 05 '22 03:10

Bohemian


return this simply means "return the reference of the current instance".

like image 45
Ousmane D. Avatar answered Oct 05 '22 04:10

Ousmane D.