In Java, this keyword is a reference to current object within an instance method or a constructor.
There are many uses of this keyword but we will peek into some major uses here.
Invoke Instance variables in a Constructor
First see the example below:
public class LearnThis {
int x;
int y;
LearnThis (int x, int y) {
x = x;
y = y;
}
public static void main(String[] args) {
LearnThis lt = new LearnThis(4,2);
System.out.println(lt.x);
System.out.println(lt.y);
}
}
Here, we can see that instance variable and constructor parameter is same. In this case, we will get 0 0 as output.
But if we write same program as:
public class LearnThis {
int x;
int y;
LearnThis (int x, int y) {
this.x = x;
this.y = y;
}
public static void main(String[] args) {
LearnThis lt = new LearnThis(4,2);
System.out.println(lt.x);
System.out.println(lt.y);
}
}
Now, we will get 4 2 as output. this keyword referenced variables of current class.
Invoke Current Class Constructor
We can also call one constructor inside another constructor with the help of this keyword. See the example below:
public class LearnThis {
public static void main(String[] args) {
ThisLearn tl = new ThisLearn(4,2);
}
}
class ThisLearn {
//constrcutor
ThisLearn() {
System.out.println("Con 0");
}
ThisLearn(int x) {
this();
System.out.println("Con " + x);
}
ThisLearn(int x, int y) {
this(x);
System.out.println("Con " + (x+y));
}
}
Here we have called different constructor inside constructors. Third constructor calls second constructor and second constructor again calls first constructor. So in this case our output will be:
Invoke Current Class Method
We can also invoke another methods of same class in any method. Take a look at this example:
public class LearnThis {
public static void main(String[] args) {
ThisLearn tl = new ThisLearn();
tl.Display();
}
}
class ThisLearn {
void Display() {
System.out.println("I am Display");
this.Method();
}
void Method() {
System.out.println("I am Method");
}
}
We can see here that inside Display we called Method with the help of this keyword. So our output is:
Constructor in Java Previous Next Method Overloading in Java
