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 reference to the current object, so you access it like any other object - this.x
is the x
property of this
. So x
is the argument passed in, which you assign to this.x
.
This is namespacing - the idea that a name for a variable only applies within a given block of code. In java, where you are working within a function belonging to the class, you are inside the namespace for that class, however, if you have another variable with the same name as an argument, it will take precedence, and you instead access the attribute via this
.
this
can also be used in other ways. For example, say I want to draw the current object to the screen in a fictional library, from within the class, I could do:
window.draw(this)
You can also call functions
this
allows us to reference the object we are currently 'inside', so we can pass the current object as an argument. This is very useful. (No pun intended).
This really has to do with how the java compiler identifies variables by their name. Function (formaal) parameters names precede class member variables. In the first example the formal parameter names are a and b and they do not collide with the member variables x and y so writing
x = a;
is logical as x can only mean the member variable class Point.
In the second example x refers both to the formal parameter name and to the member variable. Writing x within the function body refers to the parameter so if you need some other way in order to refer to the member variable x. This is done by explicitly accessing a member via the 'this' keyword.
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 :-|
If some variable/argument with same name as object's property is defined, it "overlaps" the name of that property and one should use this.var_name.
So yes, it could be written as this.x = a
, but is somewhat redundant.
"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".
In the second example one of the arguments is named x. By referencing this.x, you mean the x field/property of the class the method is part of. It could read as: Point.x = argument x
this is being used to differentiate the two, making the meaning of the code clear.