What does the class return when using "return this"?

I started to learn Java, and I could not understand one of the examples in the book “Thinking in Java”. In this example, the author presents how he states "simple use of the keyword 'this'":

//Leaf.java //simple use of the "this" keyword public class Leaf { int i = 0; Leaf increment() { i++; return this; } void print() { System.out.println("i = " + i); } public static void main(String[] args) { Leaf x = new Leaf(); x.increment().increment().increment().print(); } } 

And when it really works on the code, I can’t understand what the increment() method returns.

This is not a variable i , is this not an object x ? I just do not understand. I tried to change the program to understand it (for example, replace return this with return i or print x instead of i ), but the compiler shows me errors.

+6
source share
4 answers
 return this; 

will return the current object, i.e. the object that you used to call this method. In your case, an object x type Leaf will be returned.

+2
source

this represents an instance of the class from which the method was called. Therefore, returning this means returning this instance of the class. Thus, as the return type appears, the increment () method returns Leaf and returns the instance in which the increment () method was called.

This is why you can call:

 x.increment().increment().increment().print(); 

Because each time .increment() call .increment() you get another Sheet on which you can call all the methods inside the sheet again.

0
source

this is a keyword referencing the current instance of Leaf . When you create your first Leaf using Leaf leaf = new Leaf () , it creates a unique instance of Leaf

Alternatively, you return a Leaf instance that calls increment()

0
source

return this; returns an instance of the class on which it acts. Therefore, each call to increment() returns the same instance, and then calls increment again. You can continue to call increment() as follows:

 x.increment().increment().increment().increment().increment().increment()... 
0
source

All Articles