Although the this
in this example you are referring to the same attribute, making no difference at all, in an instance or a constructor this
is a reserved word that references 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 using this.
this
: refers to the current instance of the object
As for example in Java we can have a parameter of
a method and attribute of a class
with the same name. If we make a
reference to this variable by the principle
of the locality we will be referencing
that variable whose declaration is
in the case of the parameter. Case
we wish to reference the class attribute
and not the parameter we should use the
reserved word this
before the name of
variable.
Besides your example, see another example, more visible, in practice as it would be:
Without the this
:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
With the 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;
}
}
See more details in the documentation.
Other reserved words
See the list of reserved words defined up to version 7 of the language:
package | import | new | class | interface | Enum | Abstract | final |
Implements | extends | instanceof | public | private | protected |
super | this throw | throws | Try | catch | Finally | if | Else | for
| do while switch case | default | break | continue | Return Boolean |
byte | short | int | long double | float | char | void | strictfp |
Transient volatile | Synchronized | Native | assert | Static goto |
const | true | false | null
References
Now I get it; Thank you
– Sergio Souza Novak