-1

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 always get the same result because I'm in a loop?

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
bog
  • 1,323
  • 5
  • 22
  • 34

1 Answers1

1

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.

Community
  • 1
  • 1
Jezor
  • 3,253
  • 2
  • 19
  • 43
  • 1
    Builder is a single use case of the pattern called Fluent API, and this code clearly isn't builder. – Marko Topolnik Jun 25 '16 at 11:44
  • Well, it clearly **builds** `s` variable depending on how many times you call `f()`. [GsonBuilder](https://google.github.io/gson/apidocs/com/google/gson/GsonBuilder.html) is a good example of a builder too. All this class lacks is the distinction between builder and object that is built. It's a builder that builds itself (; – Jezor Jun 25 '16 at 11:48
  • Mutation is not building. You can't remove the essence of a concept and pretend it is still there. – Marko Topolnik Jun 25 '16 at 12:26