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

后端 未结 9 1992
北海茫月
北海茫月 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:45

    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".

提交回复
热议问题