Reputation: 10590
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.
Upvotes: 7
Views: 1152
Reputation: 68715
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.
Upvotes: 2
Reputation: 41117
return this;
returns the instance of the class it is acting on. So every call of increment()
is returns the same instance and then it calls increment
again. You can keep on calling increment()
as :
x.increment().increment().increment().increment().increment().increment()...
Upvotes: 0
Reputation: 2321
this
is a keyword that is referencing the current Leaf
instance. When you create your first Leaf
with Leaf leaf = new Leaf ()
it creates a singular instance of Leaf
Esentially, you are returning the Leaf
instance that is calling increment()
Upvotes: 0
Reputation: 8659
this
represents the instance of the class from which the method was called. So returning this
means returning this instance of the class. So, as the return type shows anyway, the increment() method is returning a Leaf
and its returning the instance in which the increment() method was called.
This is why you can call:
x.increment().increment().increment().print();
Because with each call to .increment()
you are getting another Leaf on which you can call all the methods inside Leaf again.
Upvotes: 0