I know that this
refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x
i
There are a lot of good answers, but there is another very minor reason to put this
everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this
will make it a whole lot clearer to read.
Imagine this:
public class Hello {
private String foo;
// Some 10k lines of codes
private String getStringFromSomewhere() {
// ....
}
// More codes
public class World {
private String bar;
// Another 10k lines of codes
public void doSomething() {
// More codes
foo = "FOO";
// More codes
String s = getStringFromSomewhere();
// More codes
bar = s;
}
}
}
This is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.
You will struggle to find out where foo
resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere()
for the same reason. Lastly, after you have forgotten what s
is, that bar = s
is going to give you the final blow.
Compare it to this:
public void doSomething() {
// More codes
Hello.this.foo = "FOO";
// More codes
String s = Hello.this.getStringFromSomewhere();
// More codes
this.bar = s;
}
foo
is a variable declared in outer class Hello
.getStringFromSomewhere()
is a method declared in outer class as well.bar
belongs to World
class, and s
is a local variable declared in that method.Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.