Java: this Keyword


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);
	}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s