This Keyword in Java | Use, Example

this keyword in Java is a reference variable that refers to the current class object. In other words, it holds the reference to the current class object or the same class object.

The current class object can be referred by using this reference anywhere in the class. The keyword “this” can be applied to instance variables, constructors, and methods.

It is used only within the member functions of the class. In other words, it can only be used within the non-static method of a class. This reference cannot be used outside the class.

The general syntax to use ‘this’ keyword in Java programming is as follows:

this.a;  // It calls the current class instance variable where a is an instance variable.
this.msg(); // It calls the current class instance method where msg() is an instance method.
this(int a);  // To call parameterized constructor of the current class object.

Note:

this and super keyword cannot be used in a static method and static initialization block. This will give compile-time error because static members are not bound to instances.

Prove that This Keyword refers to Current Class Object


Let’s take an example program where we will prove that the keyword ‘this’ refers to the current class object or not.

Example 1:

package thisKeyword; 
public class Hi 
{ 
  void msg() 
  { 
    System.out.println(this); // It will print the same reference ID. 
  } 
public static void main(String[] args) 
{ 
// Create an object of class Hi.
   Hi h = new Hi(); 
   System.out.println(h); // It will print the reference ID. 
   h.msg(); 
 } 
}
Output: 
       thisKeyword.Hi@1db9742 
       thisKeyword.Hi@1db9742

As you can see in the output of the above program, the address of this and object reference variable are the same. This shows that this keyword in Java refers to the current class object.

Use of This keyword in Java


In Java, there are six usages of this keyword. They are as follows:

  • this reference can be used to refer to the current class instance variable.
  • this keyword is used to call the non-static method of the current class.
  • this() can be used to invoke the current class constructor.
  • this keyword can be used as a parameter in the method call.
  • The keyword “this” can be used as a parameter in the constructor call.
  • It can also be used to return the object of the current class from the method.

Referring Current Class Instance Variable using This Keyword in Java


The “this” keyword can be used to refer current class instance variable in Java. If there is an ambiguity between instance variables and parameters, this reference can resolve the problem of ambiguity.


Understanding problem without using this keyword:

Let’s take an example program to understand the problem of ambiguity that will occur in the below program.

Example 2:

package thisKeyword; 
public class Student 
{ 
// Declare instance variables. 
   String name; 
   int rollno; 

// Declare a parameterized constructors with two parameters name and rollno. 
// Here, name and rollno are local variables. 
   Student(String name, int rollno) 
   { 
   // Here, the parameter's identifier is the same as that of the instance variables name. 
      name = name; 
      rollno = rollno; 
   } 
   void display() 
   { 
      System.out.println(name+ " "+rollno); 
   } 
public static void main(String[] args) 
{ 
 // Create an object of class Student and call the display() method using reference variable s. 
    Student s = new Student("DEEPAK", 123); 
    s.display(); 
 } 
}
Output: 
       null 0

In the above example program, the parameter’s identifier (formal arguments) is the same as that of the instance variable. It is permissible to do this in Java.

But, there occurs the problem of ambiguity between parameters and instance variables. So, we can resolve this problem by using this keyword in Java programming.

Solution to solve the above problem using this keyword:

Example 3:

public class Student 
{ 
// Declare instance variables. 
   String name; 
   int rollno; 

// Declare a parameterized constructor with two parameters name and rollno. 
// Here, name and rollno are local variables. 
   Student(String name, int rollno) 
   { 
   // Here, the parameter's identifier is same as that of the instance variables name. 
   // So, we will use this keyword to differentiate between instance variables and parameters. 
      this.name = name; // Reference to current object. 
      this.rollno = rollno; // Reference to current object. 
    } 
    void display() 
    { 
       System.out.println(name+ " "+rollno); 
    } 
public static void main(String[] args) 
{ 
 // Create an object of class Student and call the display() method using reference variable s. 
    Student s = new Student("DEEPAK", 123); 
    s.display(); 
 } 
}
Output: 
       DEEPAK 123

In the main method, the object reference variable ‘s’ is the current object in context. So, this reference stores the reference of object reference variable s.

In the parameterized constructor of class Student, this.name and this.rollno refer to the data field of current class object s. Here, the current class object means the same class object. They can also be written without using this keyword.

But as the parameters (local variables) of instance method are having the same name as instance variables of class, we have to use the keyword this.

Note:

If local variables (formal arguments) and instance variables are different, there is no need to use keyword ‘this’. For more detail, follow this tutorial: Constructor in Java.

Calling Current Class Method using This Keyword


The keyword ‘this’ can be used to call methods of the current class. If we do not write ‘this’ keyword, Java compiler automatically adds ‘this’ keyword while invoking the method. The following example in the figure shows how to add ‘this’ keyword automatically by the compiler while calling method.

Calling current class methods using this keyword in Java

Let’s take an example program where we will call the current class method using this keyword. Java compiler will automatically put “this” keyword while calling method.

Example 4:

package thisKeyword; 
public class Hello 
{ 
   void m() 
   {  
      System.out.println("Hello Java"); 
   } 
   void n() 
   { 
      m(); // method m() is called. m() is same as this.m(). Compiler automatically put this here. 
      System.out.println("Welcome you"); 
   } 
public static void main(String[] args) 
{ 
    Hello obj = new Hello(); 
    obj.n(); 
 } 
}
Output: 
       Hello Java 
       Welcome you

Returning This Reference to Method in Java


Let us consider an example program in which we will return this keyword to the method.

Example 5:

package thisKeyword; 
public class AddTest 
{ 
 // Declare an instance variable num of data type int. 
    int num; 

 // Declare one parameter constructor with parameter num. The parameter num is a local variable. 
    AddTest(int num) 
    { 
       this.num = num; // Reference to current object. 
    } 
 // Declare an instance method. 
    void show() 
    { 
       System.out.println("Number: " +this.num); 
    } 
 // Declare an instance method incr() with type class 'AddTest'. 
    AddTest incr() 
    { 
       num++; // Increment by 1. 
    // Returns this reference to the current object. 
       return this; 
    } 
public static void main(String[] args) 
{ 
  // Create an object of the class and pass argument 20 to its parameterized constructor. 
     AddTest add = new AddTest(20); 

  // Call incr() method using reference variable add and increment two times. 
     add.incr().incr(); // Call show() method using reference variable add. 
     add.show(); 
  } 
}
Output: 
       Number: 22

The method incr() returns a reference to the current object. Inside the main method, when add.incr is called using reference variable add, num is incremented to 21 and the reference of the current object is returned, which again calls the incr() method. This is done two times.

So, the number becomes 22. In the end, the show method is called using the reference variable, which displays the number: 22.

Calling Current Class Constructor using This Keyword in Java


this() keyword in Java can also be used to call another current class constructor from within a constructor. This is called an explicit invocation constructor. It is used for constructor chaining.

Key Points:

1. The invocation of another constructor using ‘this’ keyword must be the first line of constructor only. That means we cannot add this() keyword anywhere other than the first line of the constructor.

2. Java compiler never put automatically this keyword like super.

3. Recursion using ‘this’ call to the constructor is not allowed in Java.

Let’s take some example programs based on calling current class constructor using this keyword.

Calling Default Constructor from Parameterized Constructor:

Example: 6

package thisKeyword; 
public class ABC 
{ 
// Declare a default constructor. 
   ABC() 
   { 
     System.out.println("HELLO JOHN"); 
   } 
// Declare a parameterized constructor with parameter x. x is a local variable. 
   ABC(int x) 
   { 
  // This statement calls default constructor from parameterized constructor. 
     this(); // Must be the first line in the constructor. 
     System.out.println("WELCOME INDIA"); 
   } 
} 
public class ABCTest 
{ 
  public static void main(String[] args) 
  { 
 // Create an object of class ABC and pass the value to parameterized constructor. 
    ABC obj = new ABC(12); 
  } 
}
Output: 
       HELLO JOHN 
       WELCOME INDIA

In the main method of class ABCTest, when an object is created for class ABC with passing an argument 12, it calls parameterized constructor of class ABC. The keyword this in the first line of the constructor will call default constructor of class ABC and prints the output “HELLO JOHN” on the console.

After printing the first output, the control of execution again comes to the parameterized constructor and prints the output “WELCOME INDIA”.

Calling Parameterized Constructor from Default Constructor:

Example 7:

package thisKeyword; 
public class CD 
{ 
   CD() 
   { 
      this(5); // This statement will call parameterized constructor from default constructor. 
      System.out.println("Hello John"); 
   } 
   CD(int x) 
   { 
      System.out.println(x); 
      System.out.println("You are so sweet"); 
   } 
} 
public class CDclasstest 
{ 
  public static void main(String[] args) 
  { 
     CD cd = new CD(); // This statement will call default constructor.
  } 
}
Output: 
       5 
       You are so sweet 
       Hello John

In this example, we have defined a class CD which contains two constructors – a default constructor and a parameterized constructor. In the default constructor, we can see that there is a call to the parameterized constructor using “this” keyword and passing the value 5 as an argument. This is known as constructor chaining.

After the call to the parameterized constructor, the System.out.println(“Hello John”); statement will execute, which will print “Hello John” to the console. The parameterized constructor has an integer parameter x. Inside this constructor, the value of x is printed to the console, followed by the message “You are so sweet.”

Inside the main method, we have created an instance of the CD class. The default constructor of the CD class will invoke while creating an object. The default constructor of the CD class calls the parameterized constructor by passing the value 5 and then prints “Hello John” to the console.

Passing this keyword as Argument to Method call


The keyword ‘this’ in Java can be used as an argument while calling the method. It is mainly used in event handling. Let’s take an example program to understand the concept.

Example 8:

package thisKeyword; 
public class Test 
{ 
// Declare an instance method whose a parameter is t with class type Test. 
   void m1(Test t) 
   { 
      System.out.println("m1 method is called"); 
   } 
 void m2()  
 { 
   m1(this); // Passing this as an argument in the m1 method. this keyword will pass the reference of current class object to the m1 method. 
 } 
public static void main(String[] args) 
{ 
   Test t = new Test(); 
   t.m2(); // m2 method is called. 
  } 
}
Output: 
       m1 method is called

Passing This Keyword as Argument in Constructor call


We can also pass this keyword in the constructor call. This concept is useful when we have to use one object in multiple classes. Let’s take an example program to understand it better.

Example 9:

package thisKeyword; 
public class A 
{ 
   B obj; 
// Declare a parameterized constructor whose parameter is obj of class type B. 
   A(B obj) 
   { 
      this.obj = obj; 
   } 
   void show() 
   { 
      System.out.println("Show method is called"); 
      System.out.println("Value of b: " +obj.b); 
   } 
} 
public class B 
{ 
 // Declare an instance variable and initialize the value 30. 
    int b = 30; 

 // Declare a default constructor. 
    B() 
    { 
    // Create an object of class A and pass this as an argument to call the constructor of class A. 
    // this keyword will pass the reference of the current class object. Here, B is the current class object. 
       A a = new A(this); 
       a.show(); // show() method of class A is called. 
     } 
 public static void main(String[] args) 
 { 
  // Create an object of class B.
     B obj = new B(); 
  } 
}
Output: 
       Show method is called 
       Value of b: 30

Return Current Class Object using This Keyword in Java


The keyword ‘this’ can be returned as a statement from the method. In such a case, the return type of method must be class type (non-primitive). The general syntax to return this keyword is as:

return_type method_name()
{
   return this;
}

Let us consider an example in which we will return the current class object using “this” keyword in Java.

Example 10:

package thisKeyword; 
public class Animal 
{ 
// Declare an instance method show with return type Animal (class type). 
   Animal show() 
   { 
      return this; // return statement
   } 
   void msg() 
   { 
      System.out.println("Lion is an animal"); 
   } 
public static void main(String[] args) 
{ 
    new Animal().show().msg(); 
 } 
}
Output: 
       Lion is an animal

In this example, we have created a class Animal class which contains two methods: show() and msg(), and a main method. The show() method is declared with a return type of Animal, which means it returns an instance of the Animal class.

Inside the show() method, the return statement refers to the current instance of the class (Animal in this case). So, when the show() method is called, it returns the current instance of the Animal class. The msg() method is a simple method that prints “Lion is an animal” to the console.

In the main method, w have created a new instance of the Animal class and then, immediately called the show() method on that instance using the dot notation. This returns the same instance (since the show() method returns this, which is the current instance). After calling the show() method, the msg() method will call on the same instance that will print “Lion is an animal” to the console.

Advantages of This Keyword in Java


There are several benefits of using this keyword in Java. They are:

(a) By using “this,” we can prevent confusion and ambiguity between instance variables and method parameters with the same name.

(b) The use of “this” keyword improves the readability of the code by clearly indicating which variables belong to the class instance. This makes the code more understandable.

(c) “this” keyword helps when chaining methods within the same object, maintaining a consistent reference to the instance and ensuring seamless method calls.

(d) While using multiple constructors in a class, “this” simplifies the process of constructor overloading and initialization of different attributes.

(e) Explicit use of keyword “this” contributes to better code maintenance over time. It helps us easily identify where instance variables are being used.


Recommended Post

Difference between this and super keyword in Java

⇐ PrevNext ⇒

Please share your love