bogALT bogALT - 5 months ago 9
Java Question

Using reference to "this" object from member variable

I am asked to say what does this code do but I really cannot figure it out.
I've tried to execute it in netbeans and got the answer

6
but really cannot understand why.

public class Quattro {
int x = 5;
Quattro s = this;
Quattro f(){
s.s.s.x++;
return s;
}
void g(){System.out.println(x);}
public static void main (String[] args){
Quattro a4 = new Quattro();
a4.f().g();
}
}


Question 1: What does
Quattro s = this;
do? Am I declarind a pointer to my self? If so, it means that I can write

Quattro f(){
s.s.s.x++;
return s;
}


or even

Quattro f(){
s.s.s.s.s.s.s.s.x++;
return s;
}


and I'll allways get the same result because I'm in a loop?

Question 2: I do not understand what
a4.f().g();
does... seems so wired to me.

Answer

If you assign this reference to a member variable, you have a recursion. Yes, it doesn't matter how many s's you'll add, because they are always the same object, which is this object. It's the same as if you wrote:

this.this.this.this.this.this.x++;

Function f() returns reference to this object after doing some other operations on it. It's a common design pattern in Java, called builder. Adding ability to do a4.f().g(); to a class is called method chaining. In other words, f() is this object at the end of the call, just like s is, so you can do:

a1.f().f().f().f().f().f();

And it means you just called f() function from a1 object 6 times.