This article helps you understand how to use the this keyword in Java with code exampels.

Basically, the this keyword is used to refer to the current instance of a class. For example:

class Manager {
    Employees[] employees;
    
    void manageEmployees() {
        int totalEmp = this.employees.length;
        System.out.println("Total employees: " + totalEmp);
        this.report();
    }
    
    void report() { }
}
In the above example, the this keyword is used in two places:

  • this.employees.length: accesses a variable of the current instance of the class Manager.
  • this.report(): invokes a method of the current instance of the class Manager.
And the code that creates an instance of the class Manager:

Manager m1 = new Manager();
In this context, this.employees refer to the array variable Employee[] of the instance m1, and this.report() refers to a method of the instance m1.

In Java, the this keyword is often used to assign values for instance variables in constructor, getter and setter methods. For example:

public class Customer {
	private String name;
	private String email;

	public Customer(String name, String email) {
		this.name = name;
		this.email = email;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return this.name;
	}
}
In this context, the method parameters have same name as class variables so we need to use this keyword to distinguish between them.

Another usage of this keyword: You can use this keyword as a call to an overload constructor of the same class, for example:

public class Customer {
	private String name;
	private String email;

	public Customer(String name, String email) {
		this.name = name;
		this.email = email;
	}

	public Customer(String name) {
		this(name, null);
	}
}
 



Notes:

  • You cannot use this keyword to access static variables or methods - as static members belong to the static class instance - not object instance.
  • The this keyword is optional, that means if the above example will behave the same if it does not use this keyword. However, using this keyword may make the code more readable or understandable.
 

Related keyword: super. See all keywords in Java.

 

Related Topics:

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#2Nam2023-01-02 21:42
Good catch, Mareki. Corrected.
Quote
#1Marecki2023-01-01 21:01
public void getName() {
return this.name;
}
This method should be String instead of void type???
Quote