If I write the following class:
public class Example {
int j;
int k;
public Example(int j, int k) {
j = j;
k = k;
You might want to take a look at What is the advantage of having this/self pointer mandatory explicit?
Although using this
is not mandatory in Java as you noticed I'm sure it will shed some light on the subject of using this
in Java as well.
To avoid this, use an IDE (like Eclipse) and it will generate warnings in this case.
Also, make your fields final unless they absolutely can't be. There are a number of reasons (apart from this one) to do that.
In your constructor code, you are assigning variables to themselves. 'j' is the j specified in the argument for the constructor. Even if it was the class variable j defined above, then you are still saying "j = j" ... i.e. j isn't going to evaluate differently on the left and on the right.
public Example(int j, int k) {
this.j = j;
this.k = k;
}
This doesn't quite answer your question, but if you use Eclipse you might find "Assignment has no effect" setting useful. I am sure this will be in other IDEs too.
Just like Robert Grant said, 'this' is how you make it clear that you are referring to a member variable instead of a local variable.
this is useful when you want to return the object itself
return this;
This is useful because if a class has for example Method1() and Method2(), both returning this, you are allowed to write calls like
object.Method1().Method2()
Also inside a method it can be useful to pass the object itself to another function, during a call.