Can someone explain to me in detail the use of 

2019-02-27 22:09发布

I don't really understand the use of 'this' in Java. If someone could help me clarify I would really appreciate it.

On this website it says: http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

"Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this."

and it gives the following example:

For example, the Point class was written like this

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int a, int b) {
        x = a;
        y = b;
    }
}

but it could have been written like this:

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

Yet, I still don't fully understand why x = a could have been written as this.x = x? Why isn't it this.x = a? Why is the x on the left side?

I'm sorry but I am very new to Java. I apologize for boring the experts.

9条回答
时光不老,我们不散
2楼-- · 2019-02-27 22:34

The idea is to make it very clear that you are providing values for x and yin your constructor.

Problem is now that due to the scoping rules that within the constructor x refers to the passed value and not the field x. Hence x = x results in the parameter being assigned its own value and the shadowed field untouched. This is usually not what is wanted.

Hence, a mechanism is needed to say "I need another x than the one immediately visible here". Here this refers to the current object - so this.x refers to a field in the current object, and super refers to the object this object extends so you can get to a field "up higher".

查看更多
疯言疯语
3楼-- · 2019-02-27 22:37

In the second example, the arguments to the constructor are not a and b; they were changed to x and y, and this.x = x; means "assign this Point class instance's member variable x the value passed to the constructor as x".

查看更多
女痞
4楼-- · 2019-02-27 22:38

It isn't this.x = a because there isn't an 'a' in the second example. The point is that you can reuse the same variable name, which is less confusing :-|

查看更多
登录 后发表回答