To refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity. Let's understand the problem if we don't use this keyword by the example given below:


\begin{lstlisting}
class Student{
int rollno;
String name;
float fee;
St...
...nt(112,''sumit'',6000f);
s1.display();
s2.display();
}
}
\end{lstlisting}

Output:


\begin{lstlisting}
0 null 0.0
0 null 0.0
\end{lstlisting}

In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable. Solution of the above problem by this keyword


\begin{lstlisting}
class Student{
int rollno;
String name;
float fee;
St...
...nt(112,''sumit'',6000f);
s1.display();
s2.display();
}
}
\end{lstlisting}

Output:


\begin{lstlisting}
111 ankit 5000.0
112 sumit 6000.0
\end{lstlisting}

If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:


\begin{lstlisting}
class Student{
int rollno;
String name;
float fee;
St...
...nt(112,''sumit'',6000f);
s1.display();
s2.display();
}
}
\end{lstlisting}

Output:


\begin{lstlisting}
111 ankit 5000.0
112 sumit 6000.0
\end{lstlisting}