Use of 'this' Keyword in Java
The 'this' keyword in Java is used to refer to the current object of the class. It is commonly used for
the following purposes:
1. Refer to instance variables:
When local variables have the same name as instance variables, 'this' is used to distinguish them.
Example:
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
2. Invoke current class method:
'this' can be used to call another method of the same class.
Example:
void display() {
System.out.println("Display method");
}
void show() {
this.display();
3. Invoke current class constructor:
'this()' can be used to call another constructor of the same class.
Example:
class Example {
Example() {
this(10);
System.out.println("Default constructor");
Example(int x) {
System.out.println("Parameterized constructor: " + x);
4. Pass current object as a parameter:
'this' can be passed as an argument in method or constructor calls.
Example:
void show() {
helper(this);
}
void helper(Student obj) {
System.out.println(obj.id);
5. Return current object:
Useful in method chaining.
Example:
class Test {
Test getObject() {
return this;