Clarity
Another reason you might want to use this
is for code clarity.
It is a lot easier to know that a particular line refers to a field
or method on the same class if there is an explicit this.
before
the reference.1
class Elmo {
int age;
void sayHello() {
System.out.println("Hi, I'm Elmo");
System.out.print("I am ");
System.out.print(this.age);
System.out.println(" years old.");
}
}
void main() {
Elmo elmo = new Elmo();
elmo.age = 3;
elmo.sayHello();
}
1
This is very much a personal preference thing. I generally choose to write
this.
whenever I am able to for this reason.