this keyword in Java

 this keyword is java is used in various ways

  • It is used to refer current class instance variables and methods
  • It can be used to call either the parameter less constructor using this() or parameterized constructor this(parameter1, parameter2, ....)
            Note: this() call, must be the first statement in constructor
  • It can be used to return the current class instance 
 
    Let's understand each point with an example:
    Example 1:

class Employee{
    private int empId;
    private String empName;
   
    public Employee(int empId, String empName) {
        //using this keyword to access instance variables empId, empName
        this.empId = empId;
        this.empName = empName;
    }

    public int getEmpId() {
        return empId;
    }

    public void setEmpId(int empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        //accessing instance methods using this keyword
System.out.println("Employee Name has changed from " + this.getEmpName()
+ " to " + empName);
        this.empName = empName;
    }
   
}


public class Program {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Employee emp = new Employee(1, "John");
        System.out.println(emp.getEmpId() + " : " + emp.getEmpName()); //Output:1:John
        emp.setEmpName("Joe"); //Output: Employee Name has changed from John to Joe
    }

}

        If you'll notice the constructor of Employee class
        public Employee(int empId, String empName) {
        //using this keyword to access instance variables empId, empName
        this.empId = empId;
        this.empName = empName;
    }

    A question should occur in your mind, why we have used this keyword here, can't we assign the variables without using this keyword ?
    The answer is Yes, you can do this as:
        public Employee(int employeeId, String employeeName) {
        //using this keyword to access instance variables empId, empName
        empId = employeeId;
        empName = employeeName;
    }

  Notice here the parameter and instance variables names are different. Hence here we
can assign values without using this keyword.

What if instance variables and parameters names are same ?

    public Employee(int empId, String empName) {
        empId = empId;
        empName = empName;
    }
            
    Try executing above code using this constructor. Here if you'll use
       
public class Program {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Employee emp = new Employee(1, "John");
        System.out.println(emp.getEmpId() + " : " + emp.getEmpName());
        emp.setEmpName("Joe");

    }

}

Output:
        0 : null
        Employee Name has changed from null to Joe

        A null value is printed here, this is because when variables have same name as instance, JVM
consider is as a local variable instead of instance variable and assigns values to local variables, instance variables remain untouched. That is why it is printing the default value of String type as null and 0 for integer. 
    Hence we use this keyword to differentiate between instance variables and parameters/local variables with same name as instance variables.


Example 2: 
    Suppose in the above Employee class, instead of a single constructor we define multiple constructors
as below:
    public Employee() {
        System.out.println("Instance of Employee class is created");
    }
   
    public Employee(int empId, String empName) {
        this.empId = empId;
        this.empName = empName;
    }


Now if you run this code, you'll see that parameter less constructor didn't run. To call a constructor we can use this keyword as: 
   
    public Employee() {
        System.out.println("Instance of Employee class is created");
    }
   
    public Employee(int empId, String empName) {
        this(); //must be the first statement
        this.empId = empId;
        this.empName = empName;
        //this(): calling this() here will result in a compilation error
    }



Example 3: Calling parameterized constructor using this
  public Employee(float bonus) {
        System.out.println("Bonus % for employee this year: " + bonus );
    }
   
    public Employee(int empId, String empName) {
        this(3.5f); //you can pass as many arguments you want
        this.empId = empId;
        this.empName = empName;
    }
        

Example 4: return current class instance
class MyClass{  
    MyClass getClass(){  
        return this;  
    }  
    void msg(){
        System.out.println("Hello world");
    }  
}  
class Program{  
    public static void main(String args[]){  
        new MyClass().getClass().msg();  //Hello world
    }  
}


Learn more about super keyword in Java



Comments

Popular Posts