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:
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:
Related keyword: super. See all keywords in Java.