Can someone explain to me in detail the use of 'this'?

后端 未结 9 2208
北海茫月
北海茫月 2021-01-24 21:51

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/ja

9条回答
  •  野性不改
    2021-01-24 22:35

    "this" is a reference to the current object you are using. You use it when you have a name clash between a field and a parameter. Parameter takes precedence over fields.

    No clash, no need for this:

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

    But this will work, too:

    public Point(int a, int b) {
        this.x = a;
        this.y = b;
    }
    

    Name clash, need to use "this":

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

    If you did only

    public Point(int x, int y) {
        x = x;
        y = y;
    }
    

    then you would just assign parameters with its own value, which effectively does nothing.

    There are more usages of keyword "this".

提交回复
热议问题