The this keyword can be used to return 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). Let’s see the example:
package com.hotmail.henrytien;
public class ThisReturn {
public ThisReturn getThisReturn() {
return this;
}
void msg() {
System.out.println(" Hello Java");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new ThisReturn().getThisReturn().msg();
}
}
Let’s prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same.
package com.hotmail.henrytien;
public class A5 {
A5(){
System.out.println(this); //prints same reference ID
}
public static void main(String[] args) {
A5 obj = new A5();
System.out.println(obj); //prints the reference ID
}
}
output:
com.hotmail.henrytien.A5@5d748654
com.hotmail.henrytien.A5@5d748654