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 variables or instance variables, if their names are same

So, there are two cases

Case 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 employeeId;
	String employeeName;

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

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

	// 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 2 different objects
		emp1.displayEmployeeInfo();
		emp2.displayEmployeeInfo();
	}
}

Output:

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

 

Explanation:

Even after creating two objects of type Employee, when we invoked display employee info method, its 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

 

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 employeeId;
	String employeeName;

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

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

	// 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 2 different 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’s value with local variables through constructor

Also, it is clear from output that values are printing in the console for respective instances i.e.; emp1 and emp2

 

Case 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 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 employeeId;
	String employeeName;

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

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

	// 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 2 different 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 with changes in line nos. 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 one of the constructor is already doing some task, the same doesn’t need to be re-do in another constructor instead invoke constructor using this() constructor call
  • 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

Read more about constructor overloading and constructor chaining here

Note: We can’t explicitly invoke another overloaded constructor, other than the use of this() constructor call

Employee.java

package in.bench.resources.thiskeyword.example;

public class Employee {

	// instance variables
	int employeeId;
	String employeeName;

	// 1-arg parametrized constructor
	Employee(int employeeId) {
		this.employeeId = employeeId;
	}

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

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

	// 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 2 different objects
		emp1.displayEmployeeInfo();
		emp2.displayEmployeeInfo();
	}
}

Output:

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

 

Explanation:

In this example, we are creating two employee object using 2-arg constructor which in turn invokes another 1-arg constructor (constructor chaining) using this() constructor call

Other things are similar to earlier examples 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 1: display() for demo purpose
	void display() {
		System.out.println("Implicitly 'this' is inserted by compiler, if not present");
		this.displayEmployeeInfo(); // implicitly 'this' keyword inserted by compiler - line no. 13
	}

	// 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. 13

We can simply put as displayEmployeeInfo() // at line no. 13 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 employeeName;

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

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

	// 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:

In above example, 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 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 employeeName;

	// Method 1: getEmployeeInfo() method to return using this keyword
	Employee getEmployeeInfo() {
		this.employeeName = "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.employeeName);
	}
}

Output:

Employee Name : VVS Laxman

 

Explanation:

In the above example,

  • 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 variables
  • this() constructor call; is used to invoke another overloaded constructor using this keyword
  • this keyword is used to invoke instance method of the same class
  • this can be used as method argument
  • 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 with call type as parameter

That’s all about this keyword in Java

 

References:

https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

 

Read Also:

Happy Coding !!
Happy Learning !!

  • Adil

    can you please explain why this cannot be used to refer static context?