使用成员变量中的“this”对象引用

时间:2021-04-16 23:37:30

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.

我被要求说这段代码做了什么,但我真的无法理解。我试图在netbeans中执行它并获得答案6但实际上无法理解为什么。

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

问题1:Quattro s =这是什么;做?我是否指出了自己的指针?如果是这样,那意味着我可以写

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.

问题2:我不明白a4.f()。g(); ......对我来说似乎很奇怪。

1 个解决方案

#1


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:

如果将此引用分配给成员变量,则会有一个递归。是的,你要添加多少个s并不重要,因为它们总是相同的对象,就是这个对象。这跟你写的一样:

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:

函数f()在对其执行一些其他操作后返回对该对象的引用。它是Java中常见的设计模式,称为构建器。添加执行a4.f()。g()的能力;一个类称为方法链。换句话说,f()就是调用结束时的这个对象,就像s一样,所以你可以这样做:

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

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

这意味着你只需要从a1对象调用f()函数6次。

#1


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:

如果将此引用分配给成员变量,则会有一个递归。是的,你要添加多少个s并不重要,因为它们总是相同的对象,就是这个对象。这跟你写的一样:

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:

函数f()在对其执行一些其他操作后返回对该对象的引用。它是Java中常见的设计模式,称为构建器。添加执行a4.f()。g()的能力;一个类称为方法链。换句话说,f()就是调用结束时的这个对象,就像s一样,所以你可以这样做:

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

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

这意味着你只需要从a1对象调用f()函数6次。