Java this keyword examples
- Details
- Written by Nam Ha Minh
- Last Updated on 02 January 2023   |   Print Email
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:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
Comments
return this.name;
}
This method should be String instead of void type???