In Java, this is a keyword which is used to refer current object of a class. That means we can access any instance variable and method by using this keyword.
Usage of Java this keyword
class Simple {
int a;
Simple(int a){
this.a = a;
}
public static void main(String[] args) {
Simple obj = new Simple(10);
System.out.println("value of a is = " + obj.a);
}
}
Output:
value of a is = 10
In java we can call a constructor using this keyword from inside the another function.
class Simple
{
Simple()
{
// Calling constructor
this("I'm a constructor of the class Simple");
}
Simple(String str){
System.out.println(str);
}
public static void main(String[] args) {
Simple obj = new Simple();
}
}
Output:
I'm a constructor of the class Simple
This is another use of the this keyword that allows to access method. If we want to use implicit object provided by Java then use this keyword. We can also access method using object reference
class Simple
{
public void getName()
{
System.out.println("Tony Stark");
}
public void display()
{
this.getName();
}
public static void main(String[] args) {
Simple obj = new Simple();
obj.display();
}
}
Output:
Tony Stark