What is the keyword "this" in Java and when should it be used?

When working with an OOP language like Java, you’ll certainly meet the keyword this. This shot explains what this keyword is when to use it.

What is the this keyword?

Simply speaking, this is a special variable used to refer to instance members like variables or methods. More precisely, it is a reference to the current object– the one whose method or constructor is being called.

this is automatically defined in any instance method or constructor.

Common uses of this

There are many use cases of this special keyword. Here are two of the most important:

  • As a variable to avoid ambiguity
  • As an alternate constructor

Let’s discuss the details.

Using this as a variable

This is the most common reason to use this, because in Java, a parameter is usually passed in with the same name as the private member variable we are attempting to set.

Example

Let’s look the following an example.

public class Employee {
private String name, education, department;
// Consrtructor
public Employee(String name, String education, String department) {
this.name = name;
this.education = education;
this.department = department;
}
public static void main(String[] args) {
Employee newEmployee = new Employee("Sarah Lifaefi", "BSc-CS", "Security");
System.out.println("Name: " + newEmployee.name);
System.out.println("education: " + newEmployee.education);
System.out.println("department: " + newEmployee.department);
}
}

The code snippet above uses this to initialize the member variables of the current object. For instance, we assign the argument name to this.name. This makes it clear that we are assigning the value of the parameter name to the instance variable name.

Using this as a constructor

Extending a class does not necessarily allow you to access its constructors in the subclasses. If the parent class constructor is important for your subclass, then you can use this for that purpose. Doing so is called an explicit constructor invocation.

Example

Let’s take a new implementation for our Employee class.

public class Employee {
private String name, education, department;
// Consrtructors
public Employee() {
this("Sarah Lifaefi", "BS", "Security");
}
public Employee(String name) {
this(name, "BS", "Security");
}
public Employee(String name, String education, String department) {
this.name = name;
this.education = education;
this.department = department;
}
public static void main(String[] args) {
Employee newEmployee = new Employee("Sarah Lifaefi");
System.out.println("Name: " + newEmployee.name);
}
}

As you can see here we have a set of constructors. Each constructor initializes some or all of Employee's member variables.

Conclusion

this is a special variable used to refer to instance members. You can use it either as a variable or as a constructor.

this is called self in some other object-oriented languages.

Free Resources