What is This keyword?
When we have to point current object then we will use this keyword. Suppose we have created an two objects Then when first object will execute this will point first object and when second object will execute this will points second object.
This keyword is not executed in static content. When we cannot write this keyword in static method and in static main method. But it works with static variable.
For Example:
class A{
int i=20;
static int j=10;
public void test(){
System.out.println(this.i);
System.out.println(this.j); }
public static void main(){
A a = new A();
a.test(); }
Output: 20 10
We can use this keyword in constructor to call another another constructor. But there is condition that this it should but first statement in constructor. Otherwise it will not execute or will not call another constructor.
For Example:
class B{
B(){
System.out.println(“Constructor”); }
B(int i){
this();
System.out.println(“Argument Constructor”); }
public static void main(String[] args){
new B(100);
} }
Output:
Constructor
Argument Constructor