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
"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.)
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
".
The idea is to make it very clear that you are providing values for x
and y
in 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".