this keyword in Java

Posted on

this keyword 

The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.

Other uses of this keyword include :

  • It can be used to refer current class instance variable
  • It can be used to invoke or initiate current class constructor
  • It can be passed as an argument in the method call
  • It can be passed as argument in the constructor call
  • It can be used to return the current class instance

 

It can be used to refer current class instance variable : 

 

Example :

—————————————————————————————————————————————-

Output : 100   Raj

                  101   sonu

—————————————————————————————————————————————-

 

It can be used to refer current class method :

Example :

public class CurrentMethod {

int i=10;

int j=20;

void add(){

System.out.println(i+j);

}

void show(){

 

this.add();

System.out.println(“addded”);

}

public static void main(String[] args){

CurrentMethod c = new CurrentMethod ();

c.show();

}

}

—————————————————————————————————————————————-

Output : 30

added 

—————————————————————————————————————————————-

 

It can be used to refer current class constructor :

Example :

—————————————————————————————————————————————-

NOTE :  call to this must be the first statement in the constructor otherwise we will get compile time error.

Output : compile time error

—————————————————————————————————————————————