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.
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.
this
There are many use cases of this special keyword. Here are two of the most important:
Let’s discuss the details.
this
as a variableThis 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.
Let’s look the following an example.
public class Employee {private String name, education, department;// Consrtructorpublic 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
.
this
as a constructorExtending 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.
Let’s take a new implementation for our Employee
class.
public class Employee {private String name, education, department;// Consrtructorspublic 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.
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 calledself
in some other object-oriented languages.