My teacher says that when I try to access an instance variable within a method I should always use the this
keyword, otherwise I would perform a double search.
I occasionally use this
because of autocompletion (makes life easier), but I clean them up afterwards.
Remember, clarity is key. In this case, it's obvious that cont
is a class variable, but if you were writing an enormous class with piles of instance variables, you might consider using this
for clarity.
You also only need to use this
when there is a name collision, e.g.
public class Ex {
int num;
public Ex(int num) {
this.num = num;
}
}
In this example, whereas num = num would cause a collision, "this" avoids it. This is the only time it is absolutely necessary, but again, often clarity is a higher priority.
this
only applies to the case where a parameter has the same name as a class property.
public class Dog {
String name;
public Dog(String name) {
name = name; //but which name? Are we just assigning a variable to itself?
// here you could say this.name = name. Or you could rename one of the variables to resolve ambiguity
}
}
Another place that this
is often used for readability is when an inner class object is referring to a field of its containing object.
public class Foo {
String foostring;
/* snip lots of code */
private class Foohelper {
void helperMethod(String bazstring) {
Foo.this.foostring = bazstring;
// etc.
}
}
}
The compiler doesn't need this, but it makes the situation where to look for foostring
more clear. Other than this (!), I only fully qualify field names in the constructor where they may be hidden by parameter names, as many other posters have illustrated here.
[Edit: Now that I think about it, there are places the compiler needs this, e.g., if Foohelper.toString()
wants to call Foo.toString()
.]
Since everybody has given examples of disambiguating names, I will give an example when using this
help:
public class Person {
private final firstName;
private final lastName;
private final Date birthdate;
private final Address address;
@Override
public boolean equals(Object otherObject) {
if (!(otherObject instanceof Person) {
return false;
}
Person otherPerson = (Person) otherObject;
// Using this here help distinguishing the current instance and the other.
return this.firstName.equals(otherPerson.firstName)
&& this.lastName.equals(otherPerson.lastName)
&& this.birthdate.equals(otherPerson.birthDate)
&& this.address.equals(otherPerson.address);
}
}
No, only use this
when you have a name conflict such as when a method parameter has the same name as an instance field that it is setting.
It can be used at other times, but many of us feel that it simply adds unnecessary verbiage to the code.
You must use this
if required because of a name conflict, though it's better to avoid those entirely.
You may use this
if you desire. It is purely a matter of taste.
You should use this
in your schoolwork if your teacher demands it.