Java 'this' Keyword Tutorial
this keyword is a reference variable used in Java to refer to the current object.
It can be used to refer to current class instance variables, methods, and constructors strings.
Usage of Java 'this' Keyword
-
1. To refer current class instance variable
The
thiskeyword can be used to refer to the current class instance variable. If there is ambiguity between the instance variables and parameters (i.e. if they have the same name), this keyword resolves the problem of ambiguity.public class Bird { private String name; public Bird(String name) { this.name = name; } } -
2. To invoke current class constructor
The
this()constructor call can be used to invoke the current class constructor.Note: Calling `this()` must be the first statement in the constructor.public class Bird { private String name; private String color; public Bird(String name) { this.name = name; } public Bird(String name, String color) { this(name); this.color = color; } } -
3. To invoke current class method
You may invoke the method of the current class by using the `this` keyword. If you don't use `this` keyword, compiler automatically adds `this` keyword while invoking the method.
-
4. To return the current class instance
We can return the `this` keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive).
public Bird getBird() { return this; }