this keyword in Java

Posted on

this key phrase 

The this key phrase can be utilized to refer present class occasion variable. If there’s ambiguity between the occasion variables and parameters, this key phrase resolves the issue of ambiguity.

Different makes use of of this key phrase embrace :

  • It may be used to refer present class occasion variable
  • It may be used to invoke or provoke present class constructor
  • It may be handed as an argument within the methodology name
  • It may be handed as argument within the constructor name
  • It may be used to return the present class occasion

 

It may be used to refer present class occasion variable : 

 

Instance :

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

Output : 100   Raj

                  101   sonu

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

 

It may be used to refer present class methodology :

Instance :

public class CurrentMethod {

int i=10;

int j=20;

void add(){

System.out.println(i+j);

}

void present(){

 

this.add();

System.out.println(“addded”);

}

public static void major(String[] args){

CurrentMethod c = new CurrentMethod ();

c.present();

}

}

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

Output : 30

added 

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

 

It may be used to refer present class constructor :

Instance :

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

NOTE :  name to this should be the primary assertion within the constructor in any other case we’ll get compile time error.

Output : compile time error

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