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. A local scope search and then an instance scope search.
Example:
public class Test(){
int cont=0;
public void Method(){
System.out.println(cont);//Should I use This.cont instead?
}
}
I hope he is wrong, but I can't find any argument.
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.
Since everybody has given examples of disambiguating names, I will give an example when using
this
help: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 usingthis
for clarity.You also only need to use
this
when there is a name collision, e.g.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.this
is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance.See Java - when to use 'this' keyword
Also This refers current object. If you have class with variables int A and a method xyz part of the class has int A, just to differentiate which 'A' you are referring, you will use this.A. This is one example case only.
So you may say that
this keyword can be used for (It cannot be used with static methods):
Another place that
this
is often used for readability is when an inner class object is referring to a field of its containing object.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 callFoo.toString()
.]