Use of this Keyword


this Keyword with instance variables

When we use the instance variables (those belong to object) then it is always recommended to write this before the variable.
It will avoid ambiguity for the compiler when local variables have same name as that of instance variables.

this keyword is used to represent the current instance.

Below example shows how the ambiguity is caused:


/*------------------------------------------------------------*/

public class Employee
    {
        private int employeeID;
        public int GetEmployeeID()
        {
            return employeeID;
        }
        public void setEmployeeID(int employeeID)
        {
            employeeID = 21;   // Refers local variable and not the class variable
        }
    }

 /*------------------------------------------------------------*/


Below program shows how the ambiguity is removed by this keyword.


/*-------------------------------------------------------------*/

public class Employee
{
    private int employeeID;
    public int GetEmployeeID()
    {
        return this.employeeID;
    }
    public void setEmployeeID(int employeeID)
    {
        this.employeeID = employeeID; // Refers instance variable and not the local variable.
    }
}

/*-------------------------------------------------------------*/


Hence it is always recommended to use this keyword when we are referring instance variables/Methods.

Note: this keyword can not be used with static variables and methods as they belong to class and not instance. for more details refer static section.


No comments:

Post a Comment