The this
keyword in Java is a reference to the current object of a class. It can be used to refer to the current object’s instance variables, methods, and constructors.
Usases of this keyword
There are a few common use cases for the this
keyword in Java:
- To call the constructor from another constructor
- To disambiguate between instance variables and parameters
- To pass the current class object as an argument
- To return the current class instance
Call a constructor from another constructor
If a class has multiple constructors, we can use the this
keyword to call one constructor from another. For example:
public class MyClass {
private int value;
public MyClass(int value) {
this.value = value;
}
public MyClass() {
this(0); // calls the MyClass(int value) constructor
}
}
Disambiguate between instance variables and parameters
Using this
to disambiguate between instance variables and parameters with the same name: If a method has a parameter with the same name as an instance variable, we can use the this
keyword to refer to the instance variable. For example:
public class MyClass {
private int value;
public void setValue(int value) {
this.value = value;
}
}
Pass the current class object as an argument
Using this
to pass the current object as an argument: We can use the this
keyword to pass the current object as an argument to a method or constructor. For example:
public class MyClass {
private int value;
public MyClass(int value) {
this.value = value;
}
public void printValue() {
System.out.println(value);
}
public void doSomething(MyClass other) {
other.printValue();
}
public void callDoSomething() {
doSomething(this);
}
}
Return the current class instance
Using this
to return the current object from a method: You can use the this
keyword to return the current object from a method. This can be useful for chaining method calls. For example:
public class MyClass {
private int value;
public MyClass setValue(int value) {
this.value = value;
return this;
}
public void printValue() {
System.out.println(value);
}
public static void main(String[] args) {
new MyClass().setValue(5).printValue();
}
}
In this example, the setValue
the method returns the current object, so we can chain the call to the printValue
method.
Conclusion
In this blog post, we learn what is this keyword and the common use cases of the this
keyword in Java.
Leave a Reply