I started learning Java and I couldn't understand one of examples in "Thinking in Java" book. In this example author represent, as he state "simple use of 'this' keyword":
//Leaf.java
//simple use of the "this" keyword
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();
}
}
And when above code is working as indeed, I cant understand what increment() method is returning.
It's not variable i, it's not object x? I just don't get it. I tried to modify program to understand it (like replace return this with return i or print x instead of i), but compiler shows me errors.
return this;
will return the current object i.e. the object which you used to call that method. In your case object x of type Leaf will be returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With