Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is returning class when use "return this"?

Tags:

java

I started learning Java and I couldn't understand one of examples in "Thinking in Java" book. In this example author represent, as he state "simple use of 'this' keyword":

//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 above code is working as indeed, I cant understand what increment() method is returning.

It's not variable i, it's not object x? I just don't get it. I tried to modify program to understand it (like replace return this with return i or print x instead of i), but compiler shows me errors.

like image 851
blekione Avatar asked Mar 20 '14 00:03

blekione


1 Answers

return this;

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

like image 184
Juned Ahsan Avatar answered Oct 16 '22 19:10

Juned Ahsan