Using this in Java

How the increment method call works in the following code:

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

      

+3


source to share


3 answers


This is an example of a method chaining .

By returning this

, subsequent calls to the instance methods of the original object instance can be made in the chain.



Each call increment()

increments the value i

by 1 because the call acts on an instance of the original object.

Finally, it print()

is called on the original object instance to output the value i

.

+4


source


Here's the code we're trying to run:

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

      

And here is the method we have:

Leaf increment() {
    i++;
    return this;
}

      

He called a chain of methods. Let's see what happens if we don't return this

:



void increment() {
    i++;
}

      

And the code will look like this:

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

      

Cm? It's just easier to return an object and call method calls.

+1


source


It increments one field of the object int i

and then returns a reference to the object the method was called on increment()

, so you can call again increment()

after point. for the same sheet.

0


source







All Articles