In Java, this keyword used as a reference variable that refers to the current object. Java this keyword having many uses:
- this to refer current class instance variable.
- this to invoke current class method (implicitly)
- this() to invoke the current class constructor.
- this to pass as an argument in the method call.
- this to pass as an argument in the constructor call.
- this to return the current class instance from the method.
this Keyword: Example
In the highlighted lines, you will see all the ways of using this keyword
public class Employee { private int employeeId; protected String name; protected String citizenship; private String department; private int salary; public Employee() { } public Employee(int employeeId, String name, String department, String citizen) { // this keyword to resolve name ambiguity this.name=name; this.citizenship=citizen; this.employeeId = employeeId; this.department = department; } public Employee(int employeeId, String name, String department, String citizen, int salary) { // this keyword use to call another constructor this(employeeId, name, department, citizen); this.salary = salary; System.out.println("Employee Constructor Executed."); } public void display() { // this to call method and pass as argument this.print(this); } public Employee getEmployee(){ //This keyword to return current object return this; } public void print(Employee employee) { System.out.println("Id :" + employeeId + ", Department :" + department + ", Salary:" + salary + ",Citizen:" + citizenship + ",Name:" + name); } }
You must log in to post a comment.