this keyword in Java
Java supports the use of ‘this’ keyword which is a reference variable. You can use ‘this’ keyword in below scenario-
- The current class instance variable can be referred to using this keyword.
- It will allow you to invoke the current class method and constructor.
- You can pass ‘this’ keyword as an argument during the method and constructor calls.
- The current class instance will be returned from the method using this keyword.
We will discuss how ‘this’ keyword will achieve this.
Referring to the current class instance variable
This keyword will be used to refer to the current class instance variable. It allows you to resolve the ambiguity problem between the instance variable and the parameters.
Example with and without the ‘this’ keyword
Without ‘this’ |
With ‘this’ |
Output-
|
Output-
|
Invoking a current class method
This keyword will allow you to invoke the method of the current class. If you are not using ‘this’ keyword then the compiler will add this keyword automatically while method invocation.
Example-
class Demo{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
this.m();
}
}
class ThisDemo{
public static void main(String args[]){
Demo a=new Demo();
a.n();
}}
Output-
hello n
hello m
Invoking the current class constructor
You can call the current class constructor by creating this() constructor. It allows you to reuse the constructor which can be used for constructor chaining.
Example-
class Demo{
Demo(){System.out.println("hello a");}
Demo(int x)
{
this();
System.out.println(x);
}
}
class ThisDemo{
public static void main(String args[])
{
Demo a=new Demo(10);
}
}
Output-
hello a
10
Passing this keyword as a method argument
You can also pass this keyword as a method argument. It can be mainly used during event handling.
Example-
class Demo{
void m(Demo obj){
System.out.println("invoking method");
}
void p(){
m(this);
}
public static void main(String args[])
{
Demo s1 = new Demo();
s1.p();
}
}
Output-
invoking method
Passing argument during the constructor call
You can pass this keyword while calling the constructor. It allows you to use a single object within many classes.
Example-
class Demo{
A4 obj;
Demo(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
Demo b=new Demo(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output-
10
Using this keyword to return the current class instance
If you are using ‘this’ keyword to be returned from the method then the return type should be the class type.
Example-
class Demo{
Demo getA()
{
return this;
}
void msg()
{
System.out.println("Hello java");
}
}
class ThisDemo{
public static void main(String args[]){
new A().getA().msg();
}
}
Output-
Hello java