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.
The idea is to make it very clear that you are providing values for
x
andy
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 fieldx
. Hencex = 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 - sothis.x
refers to a field in the current object, andsuper
refers to the object this object extends so you can get to a field "up higher".In the second example, the arguments to the constructor are not
a
andb
; they were changed tox
andy
, andthis.x = x;
means "assign this Point class instance's member variablex
the value passed to the constructor asx
".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 :-|