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.
Your teacher is correct that it will result in double search for compiler if you don't make use of this
keyword. First the compiler will search at local scope and then the instance scope if the compiler is unable to find the variable at local scope.
Also, while the compiler is converting your code to bytecode, the compiler will prefix all the instance variables with this
keyword. So, if you yourself make use of this
keyword, you are actually reducing the burden to the compiler and the code will be compiled faster.
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.
public class Test
{
int a;
public void testMethod(int a)
{
this.a = a;
//Here this.a is variable 'a' of this instance. parameter 'a' is parameter.
}
}
So you may say that
this keyword can be used for (It cannot be used with static methods):
1)To get reference of an object through which that method is
called within it(instance method).
2)To avoid field shadowed by a method or constructor parameter.
3)To invoke constructor of same class.
4)In case of method overridden, this is used to invoke method of current class.
5)To make reference to an inner class. e.g ClassName.this