'this' reference in Java


The this keyword

'this' keyword is used to refer to the current object in action. Following are the scenarios where this keyword is used.

  • It is used to differentiate the arguments passed vs the instance variables.

  • It is used to invoke the current class constructor.

  • It is used to return the current object.

  • It is used to pass the current object as a method parameter.

  • It is used to call the current object's method.

  • It is used to pass current object as a constructor argument.

Example

Create a java class named Tester.

Tester.java

Live Demo

public class Tester {
   private int a, b;

   //Scenario 1:
   //Used to differentiate the arguments passed v/s the instance variables.
   public Tester(int a, int b) {
      this.a = a;// a = a has no effect, so 'this' is required.
      this.b = b;
   }

   //Scenario 2:
   //Used to invoke current class constructor
   public Tester() {
      this(0,0);//Tester(0,0) : throws error: Method Tester is undefined.
   }

   //Scenario 3:
   //Can be used to return the current object
   public Tester getCurrentObject() {
      return this;
   }

   //Scenario 4:
   //Can be used to pass the current object
   private void display(Tester tester) {
      tester.display();
   }

   public void displayValues() {
      display(this);
   }

   //Scenario 5:
   //Can be used to call the current object's method
   public void print() {
      this.display();
   }
    //Scenario 6:
   //Can be used to pass current object as a constructor argument.
   public Tester(Tester tester) {
      this.a = tester.a;
      this.b = tester.b;
   }

   public void display() {
      System.out.println("a = " + a + ", b = " + b);
   }

   public static void main(String args[]) {
      Tester tester = new Tester(1,2);
      System.out.println("Scenario 1: ");
      tester.display();

      Tester tester1 = new Tester();
      System.out.println("Scenario 2: ");
      tester1.display();

      System.out.println("Scenario 3: ");
      tester.getCurrentObject().display();

      System.out.println("Scenario 4: ");
      tester.displayValues();

      System.out.println("Scenario 5: ");
      tester.print();

      Tester tester2 = new Tester(tester);
      System.out.println("Scenario 6: ");
      tester2.display();    
   }
}

Output

Compile and Run the file to verify the result.

Scenario 1:  
a = 1, b = 2
Scenario 2:  
a = 0, b = 0
Scenario 3:  
a = 1, b = 2
Scenario 4:  
a = 1, b = 2
Scenario 5:  
a = 1, b = 2
Scenario 6:  
a = 1, b = 2

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 18-Jun-2020

229 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements