What is ‘this’
'this' means the object whose code is being executed right now.
'this' is a keyword in java.
A keyword is a reserved word that has a different meaning which is known to the compiler.
This article will explain what does 'this' mean, its purpose and usage with explanation and examples.

Meaning of ‘this’
'this' refers to the current executing object or the object whose methods are being executed at that instant. It is a reference which points to the current object.
You can also say that 'this' is a pointer to current executing object.

Following illustration will help in understanding what is meant by current executing object.
this keyword meaningSuppose an object of a class is created. This object calls one of its method.
Now, inside the invoked(or currently executing) method, 'this' will refer to the current object(which was used to invoke the method).

In simpler words, 'this' will refer to the object which called this method.
Since 'this' refers to the current object, you can invoke its methods and access its properties using 'this' as shown in the above image.

Current object and ‘this’
To demonstrate that 'this' is in fact the object in execution currently, have a look at below program.

public class Book {

   private String title;
   private int pages;

   // class method	 
   public void translate() {
      // print this here
      System.out.println("Object executing the method: " + this);
   }

   // main method
   public static void main(String[] args) {
      // create an object of class
      Book book = new Book();
      // print this object
      System.out.println("Object created in class: " + book);
      // invoke class method
      book.translate();	
   }
}

Above program creates an object of a class and invokes a method of the same class.
Created object is printed before invoking the method and inside the method, this is printed.

Check out the output

Object created in class: Book@27082746
Object executing the method: Book@27082746

Look, both objects are same.
static and ‘this’
'this' always refers to an object while static keyword refers to a class.
In static context, there is no object. Hence, you can not use 'this' inside a static method or a static block.
Trying to do so, will result in a compiler error “Cannot use this in static context”.
Thus, there is no 'this' in main method.

Use of ‘this’
'this' keyword has many benefits when it comes to objects. Below are the important examples of using ‘this’ in java.
1. Constructor chaining
A class can have multiple constructors. It might be required to invoke one constructor from another.
This is called constructor chaining.
A constructor can be invoked from another constructor using 'this' followed by the parenthesis.
Arguments required by the constructor being invoked are supplied between parenthesis. Example,

public class Book {

   private String title;
   private int pages;

   // construtor 1	 
   public Book() {
      // invoke constructor 3
      this("", 0)
   }

   // constructor 2
   public Book(String title) {
      // invoke constructor 3
      this(title, 0)
   }
   // constructor 3
   public Book(String title, int pages) {
   }
}

In the above example, a class contains 3 constructors.
Each of the two constructors invoke the third constructor using 'this'.
2. Refer class variables
'this' refers to an object of a class, hence it can be used to access variables of its class.
Variables or fields are accessed using 'this' followed by the dot(.) operator and the name of field.
Example,

public class Book {

   public String title;

   // class method	 
   public void translate() {
      System.out.println("Title of book is : " + this.title);
   }

   // main method
   public static void main(String[] args) {
      // create an object of class
      Book book = new Book();
      // set title
      book.title = "Great Expectations";
      // invoke class method
      book.translate();	
   }
}

Above example creates an object of a class, initializes it field and invokes its method.
Inside the method, the field of class is accessed using ‘this’.
Though 'this' is redundant here since the compiler implicitly places 'this' before a class field is accessed.
3. Refer class methods
As class fields are accessed, methods of a class can also be accessed using 'this'. This is generally used to invoke one method from another.
Class methods methods are invoked by using dot(.) followed by the method name after 'this', followed by any arguments accepted by the method.
Example,

public class Book {

   public String title;

   // class method	 
   public void translate() {
      // invoke class method
      this.printTitle(this.title);
   }

   print printTitle(String t) {
      System.out.println("Title of book is : " + t);
   }

   // main method
   public static void main(String[] args) {
      // create an object of class
      Book book = new Book();
      // set title
      book.title = "Great Expectations";
      // invoke class method
      book.translate();	
   }
}

Above example invokes a class method from another class method using 'this'.
Although the method can be invoked without using 'this' as well, since the compiler implicitly inserts 'this'.
4. Supplying current object
There are class methods that accept an object of a class as argument.
If these methods are invoked from a class, then 'this' can be supplied as argument.
Below example will clarify the concept.

public class Book {

   public void translate() {
      Publisher p = new Publisher();
      // supply current book object as parameter
      p.publish(this);
   }

   // main method 
   public static void main(String[] args) { 
      // create an object of class 
      Book book = new Book(); 
      // set title 
      book.title = "Great Expectations"; 
      // invoke class method 
      book.translate();
    }

}

public class Publisher {

   // requires a book object
   public void publish(Book book) {
     // code
   }

}

A class Publisher contains a method that requires an object of class Book as argument.

Notice how the current executing book object is supplied using 'this' as argument, to the method of Publisher class when it is invoked.
5. Returning current object
As current object can be supplied as method argument, it can also be returned using 'this'. Example,

public class Transformer {

   public Transfomer transform() {
      // make changes to object
      return this;
   }
}

This class has a method which when invoked, makes some changes to the object and then returns the modified object.
Notice how it returns the object using 'this'.
6. Passing object as constructor argument
Just as this can be used to supply an object to a method argument, it is also used to provide an object as constructor argument as shown below.

public class Book {

   public void publish() {
      // supply current object as constructor argument
      Publisher p = new Publisher(this);
      // more code
   }

}


public class Publisher {

   Book book;
   
   // constructor 
   public Publisher(Book b) {
      book = b;
   }

}

Notice how the Publisher constructor is supplied the current book object as argument using 'this'.
Resolving field ambiguity with ‘this’
Constructor of a class is used to initialize fields of a class. A parameterized constructor accepts arguments which initialize class fields.
Many times same names for constructor arguments and class fields(or instance variables) are used as shown in the below example.

 class Book {
   private String title;
   private int pages;
   

   // constructor
   public Book(String title, int pages) {
      // initialize class fields
      title = title;
      pages = pages;
   }
   
   public String getTitle() {
      return title;
   }

   public int getPages() {
      return pages;
   }
 
   // main method
   public static void main(String[] args) {
      // create object
      Book book = new Book("Great expectations", 250);
      // print field values
      System.out.println("Page count: " + book.getPages());
      System.out.println("Title: " + book.getTitle());	
   }
}

This example creates an object of the class using a parameterized constructor.
The constructor initializes fields of its class using the values provides as arguments.
Note that the names of constructor arguments and class fields are the same.

Now when the program is executed and the values of fields of the class are printed, below is the output.

Page count: 0
Title: null

What happened here?
Values were provided but still they are not initialized.
This is because when the names of arguments and class fields are same, the compiler thinks that you are assigning the class fields with their own values.
Hence, it assigns the current value of fields back to them.
Thus, when they are printed, default values as per the data type of the fields are printed.

To resolve this problem, 'this' is used. Modified constructor is shown below.

public Book(String title, int pages) {
      // initialize class fields
      this.title = title;
      this.pages = pages;
   }

Now execute the program again and below output is produced.

Page count: 250
Title: Great Expectations

In this case, the compiler is able to distinguish between class fields and the constructor arguments and thus assigns them properly.

Hope the article was useful and helped in explaining the concept of 'this' in java.

Leave a Reply