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