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();
}
}
source to share
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
.
source to share
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.
source to share