blekione
blekione

Reputation: 10590

How to understand what method is returning when "return this" is used

I'm reading "Thinking in Java" and in paragraph where this keyword is explained, author use below example

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();
    }
}

What I wonder is, how to understand what the increment() method is returning? The author explains, that it returns reference to the current object. Does this mean that statement x.increment() is returning a kind of x (I know what reference mean)? And start statement x.increment().increment().increment().print(); after performing first x.increment(), became x.increment().increment().print();?

It sounds logical to me, but I'm not sure if I understand it right.

Upvotes: 1

Views: 179

Answers (3)

Andres
Andres

Reputation: 10725

You can visualize this as a hidden parameter that contains a reference to the instance on which the method is executed. To know what this contains on each execution, you have to look to what's at the left of the point that separates the method from the instance.

Upvotes: 1

Mureinik
Mureinik

Reputation: 311893

return this returns the current instance, which is quite convenient if you want to keep applying changes to it.

A great example from the JDK is StringBuilder. E.g., there's nothing wrong with this code:

StringBuilder builder = new StringBuilder();
builder.append("welcome");
builder.append("to");
builder.append("StackOverflow");

But doesn't this look much better?

StringBuilder builder = new StringBuilder().append("welcome").append("to").append("StackOverflow");

Upvotes: 3

dkatzel
dkatzel

Reputation: 31648

The method signature of increment() is

Leaf increment() 

which says it returns a Leaf instance.

The return this means to return the instance of the Leaf class that is being invoked (which in your case is referred to as x ).

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

is the same as

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

Upvotes: 1

Related Questions