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

Output:

i=3

Till now I know that the this keyword is used to produce the reference to the object that the method has been called for. So in this code, the object x is calling the method increment and the this keyword gives a reference to x. But then, how does that help one in performing multiple increments as in the following line?

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

Vinoth Krishnan
  • 2,925
  • 6
  • 29
  • 34
Student
  • 119
  • 1
  • 1
  • 12

2 Answers2

5

You have posted an example of method chaining; the linked Wikipedia entry says (in part)

Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.

In x.increment().increment().increment().print(); each increment() is chained to the next call. And, increment begins with i++ so each call increases i by 1. It is functionally equivalent to

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

See also, the StringBuilder.append() methods; they also return this to allow method chaining like

System.out.println(new StringBuilder("Hello ").append("World"));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Nothing fancy or vague is going on here, the question is how does that help one in performing multiple increments as in the following line? You are calling the the increment() method thrice, as simple as that, the increment method id returning an object that class only so the increment method can be called again. So if x is an object of type Leaf, x.increment is also an object of type Leaf(return type of increment is Leaf), so increment method can be called again. Every time the increment method is being called we are incrementing the i by 1. Pleae let me know if its still not clear.

viveksinghggits
  • 661
  • 14
  • 35