Java: this keyword

In this article, we will discuss this keyword in Java

this keyword in java is used to refer the current instance of the class

Usage of this keyword in Java

  • Instance variable: this keyword is used to refer the current instance variables of the class
  • Class constructor: this() constructor call; is used to invoke other overloaded constructor of the same class
  • Instance method: <methodName> is used to invoke current instance method of the same class
  • Method parameter: this keyword can be used to pass as argument in method invocation
  • Return type: this keyword can be used to return current class instance

Note: this cannot be used to refer anything in static context

 

Let us understand each one in detail with examples

Usage 1: this keyword with instance variables

  • this keyword helps to distinguish between local and instance variables, if their names are same
  • So, there arises 2 cases

Case 1.1. When identifier-name of local-variable and instance-variable are same

Employee.java

package in.bench.resources.thiskeyword.example;

public class Employee {

	// instance-variables
	int empId;
	String empName;

	//	2-arg parameterized constructor
	Employee(int employeeId, String employeeName) {
		// warn: The assignment to variable empId has no effect
		employeeId = employeeId; 
		// warn: The assignment to variable empName has no effect
		employeeName = employeeName; 
	}

	// display() method to print employee info
	void displayEmployeeInfo() {
		System.out.print("Employee Id : " + empId);
		System.out.println("\tEmployee Name : " + empName);
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		// creating object of type Employee
		Employee emp1 = new Employee(1001, "Rahul Dravid");
		Employee emp2 = new Employee(1002, "VVS Laxman");

		// invoking display() method using newly created objects
		emp1.displayEmployeeInfo();
		emp2.displayEmployeeInfo();
	}
}

Output:

Employee Id : 0	Employee Name : null
Employee Id : 0	Employee Name : null

Explanation:

  • Even after creating 2 objects of type Employee, when we invoked display() method to print employee details, it is printing default values for integer and string variables
  • Reason: Though, assignment is done we haven’t set the values for any specific instance
  • Note: Compiler warns with message “The assignment to variable <identifierName> has no effect

Solution for above problem :-

  • To overcome this problem we will use this keyword which will set the values for current referring instance
  • below example is exactly same as that of above example with changes in line no. 11 and 12
  • here, we are explicitly assigning current instance-variables to local-variables using this keyword

Employee.java

package in.bench.resources.thiskeyword.example;

public class Employee {

	// instance-variables
	int empId;
	String empName;

	//	2-arg parameterized constructor
	Employee(int empId, String empName) {
		this.empId = empId;
		this.empName = empName;
	}

	// display() method to print employee info
	void displayEmployeeInfo() {
		System.out.print("Employee Id : " + empId);
		System.out.println("\tEmployee Name : " + empName);
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		// creating object of type Employee
		Employee emp1 = new Employee(1001, "Rahul Dravid");
		Employee emp2 = new Employee(1002, "VVS Laxman");

		// invoking display() method using newly created objects
		emp1.displayEmployeeInfo();
		emp2.displayEmployeeInfo();
	}
}

Output:

Employee Id : 1001	Employee Name : Rahul Dravid
Employee Id : 1002	Employee Name : VVS Laxman

Explanation:

  • With the use of this keyword, we are assigning instance-variable value with local-variable through constructor
  • Also, it is clear from output that values are printing in the console for respective instance variables i.e.; emp1 and emp2

 

Case 1.2. When identifier name of local variable and instance variable are different

  • Variable Hiding: Earlier case is variable hiding scenario where local variable hides instance variables. So, to overcome this problem we have used this keyword
  • But, if identifier name of local variable and instance variable are different then there is no need of this keyword
  • Note: But the use of this keyword doesn’t affect/impact any assignment

Let us see an example on this case

Employee.java

package in.bench.resources.thiskeyword.example;

public class Employee {

	// instance variables
	int empId;
	String empName;

	//	2-arg parametrized constructor
	Employee(int eid, String eName) { 	// line no. 10
		empId = eid;				// line no. 11
		empName = eName;			// line no. 12
	}

	// display() method to print employee info
	void displayEmployeeInfo() {
		System.out.print("Employee Id : " + empId);
		System.out.println("\tEmployee Name : " + empName);
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		// creating object of type Employee
		Employee emp1 = new Employee(1001, "Rahul Dravid");
		Employee emp2 = new Employee(1002, "VVS Laxman");

		// invoking display() method using newly created objects
		emp1.displayEmployeeInfo();
		emp2.displayEmployeeInfo();
	}
}

Output:

Employee Id : 1001	Employee Name : Rahul Dravid
Employee Id : 1002	Employee Name : VVS Laxman

Explanation:

  • Above program is same as that of earlier 2 programs with changes in line no. 10, 11 and 12

 

Usage 2: this() keyword with constructor

  • this() constructor call; is used to invoke another overloaded constructor in the same class
  • if overloaded constructor-1 is already doing some task, then another overloaded constructor-2 doesn’t neccessarily need to do same task again; instead invoke constructor using this() constructor call with necessary parameters
  • this() constructor call; helps in removing redundant code and better re-usability
  • if this() constructor call is present, then it must be first line of the constructor, otherwise compiler throws error
  • invoking one constructor from another constructor is known as constructor chaining in Java
  • Note: We can’t explicitly invoke another overloaded constructor, other than the use of this() constructor call

Read more about constructor overloading and constructor chaining here

Employee.java

package in.bench.resources.thiskeyword.example;

public class Employee {

	// instance variables
	int empId;
	String empName;

	// 1-arg parameterized constructor
	Employee(int empId) {
		this.empId = empId;
	}

	//	2-arg parametrized constructor
	Employee(int empId, String empName) {
		this(empId);
		this.empName = empName;
	}

	// display() method to print employee info
	void displayEmployeeInfo() {
		System.out.print("Employee Id : " + empId);
		System.out.println("\tEmployee Name : " + empName);
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		// creating object of type Employee
		Employee emp1 = new Employee(1001, "Rahul Dravid");
		Employee emp2 = new Employee(1002, "VVS Laxman");

		// invoking display() method using newly created objects
		emp1.displayEmployeeInfo();
		emp2.displayEmployeeInfo();
	}
}

Output:

Employee Id : 1001	Employee Name : Rahul Dravid
Employee Id : 1002	Employee Name : VVS Laxman

Explanation:

  • We are creating 2 employee objects using 2-arg constructor which in turn invokes another overloaded 1-arg constructor (constructor chaining) using this() constructor call
  • Other things are similar as stated in the earlier example to display employee info

 

Usage 3: this keyword with method invocation of current class

Syntax: this.<method_Name>();

  • this keyword is used to invoke current class’s instance method invocation
  • Compiler inserts this keyword for current class’s method invocation, if not present in the method call

Employee.java

package in.bench.resources.thiskeyword.example;

public class Employee {

	// Method 1: displayEmployeeInfo() to print employee info
	void displayEmployeeInfo() {
		System.out.println("Displaying employee info");
	}

	// Method 2: display() for demo purpose
	void display() {
		System.out.println("Implicitly this keyword "
				+ "is inserted by compiler, if not present");
		// implicitly 'this' inserted by compiler - line no. 15
		this.displayEmployeeInfo(); 
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		// creating object of type Employee
		Employee emp1 = new Employee();

		// invoking display() using object reference
		emp1.display();
	}
}

Output:

Implicitly 'this' is inserted by compiler, if not present
Displaying employee info

Explanation:

  • Instead of this.displayEmployeeInfo() // at line no. 15
  • We can simply put as displayEmployeeInfo() // at line no. 15 as this keyword is inserted during compilation process by compiler

 

Usage 4: this keyword with method parameter

  • this keyword can be used to pass as argument in method invocation

Employee.java

package in.bench.resources.thiskeyword.example;

public class Employee {

	// instance variable
	String empName;

	// 1-arg parametrized constructor
	Employee(String empName) {
		this.empName = empName;
	}

	// Method 2: displayEmployeeInfo() method to print emp-info
	void displayEmployeeInfo(Employee employee) {
		System.out.println("Employee Name : " + employee.empName);
	}

	// Method 1: display() method for demo purpose
	void display() {
		displayEmployeeInfo(this);
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		// creating object of type Employee
		Employee emp1 = new Employee("Rahul Dravid");
		emp1.display();
	}
}

Output:

Employee Name : Rahul Dravid

Explanation:

  • While invoking a method with Employee object we are explicitly passing this which indicates the current instance
  • So, it is one of the way to pass method parameter using this for current instance

 

Usage 5: this keyword with return type

  • Return type :- this keyword can be used to return current class’ instance
  • Syntax :-
return_type method_name() {
       return this;
}
  • Note :- To return this keyword (current instance) from method, we need to have return-type as current class-type; otherwise it won’t work

Employee.java

package in.bench.resources.thiskeyword.example;

public class Employee {

	// instance variable
	String empName;

	// Method 1: getEmployeeInfo() method to return using this
	Employee getEmployeeInfo() {
		this.empName = "VVS Laxman";
		return this;
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String[] args) {

		// creating object of type Employee
		Employee emp1 = new Employee();
		emp1.getEmployeeInfo();

		// printing employee name into console
		System.out.println("Employee Name : " + emp1.empName);
	}
}

Output:

Employee Name : VVS Laxman

Explanation:

  • We are returning this as return value
  • But before that, we are setting employee name using this keyword
  • finally when control return back, we are printing employee-name in the console
  • So, this can be used to return type

 

Point to remember about this keyword:

  • this is used to refer current class’s instance
  • this can be used to refer instance-variable of same class
  • this() constructor call; is used to invoke another overloaded constructor using this keyword in the same class
  • this keyword is used to invoke instance-method of the same class
  • this can be used as method-argument, when invoking method
  • this can be used to return-value from instance-method, provided return-type of method is current class’ type
  • this can be used in constructor-call, while invoking overloaded constructor

That’s all about this keyword in Java

 

References:

 

Read Also:

 

Happy Coding !!
Happy Learning !!

Java: super keyword
Java: static keyword