Although
this
in this example is referring to the same attribute, making no difference, 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 that.
this
: refers to the current instance of the object
As for example in Java we can have a parameter of
a method and an attribute of a class
with the same name. If we make a
reference to this variable, on the principle
of the locality we will be referencing
that variable whose declaration is
in the case the parameter. Case
we want to reference the class attribute
and not the parameter we should use the
reserved word this
before the name of the
variable.
In addition to your example, see another example, more visible in practice as it would be:
Without this
:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
With 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 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 | end |
implements | extends | instanceof | public | private | protected |
super | this throw | throws | try | catch | finally | if | else | for
| 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