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

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

    "This" is a hidden "argument" that gets passed for you so that the methods that operate on the object know which object exactly they are to operate on.

    Now imagine you pass the argument of name "x" but the class does have that var name defined already. What happens ? Well, the name x that "belongs" to the object and the argument x are not the same data-object yet they share the name.

    In order to disambiguate, you need to say explicitly "this.x", which tells the compiler that you're talking about the x that already belongs to "this" object. (That is, the current object you're trying to operate on.)

    0 讨论(0)
  • 2021-01-24 22:39

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

    0 讨论(0)
  • 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".

    0 讨论(0)
提交回复
热议问题