This Keyword in Java | Uses & Example programs - Scientech Easy

This Keyword in Java | Uses & Example programs

This Keyword in Java


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 same class object. The current class object can be referred by using this reference to anywhere in the class. The keyword this can be applied to instance variables, constructors, and methods. It is used only inside the class i.e only inside the member functions of the class and can only be used within the non-static function of the class. This reference cannot be used outside the class. 
The syntax to use 'this' keyword in Java is given below:
Syntax:
    this.a;  // variable case where a is an instance variable.
    this.msg(); // method case
    this(int a);  // To call parameterize constructor of 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.

Usage of this keyword in Java


There is six usage of Java this keyword. They are the following:
1. this reference can be used to refer to the current class instance variable.
2. this keyword is used to call the non-static method of the current class.
3. this() can be used to invoke the current class constructor.
4. this keyword can be used as a parameter in the method call.
5. The keyword this can be used as a parameter in the constructor call.
6. 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


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

Understanding the problem without using this keyword


Let's take a simple example program to understand the problem of ambiguity that will occur in the given below program.
Program source code 1:
    package com.thisKeyword; public class Student { // Declare instance variables. String name; int rollno; // Declare a parameterized constructor with two parameters such as 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. 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 the 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.
Program source code 2:
    public class Student { // Declare instance variables. String name; int rollno; // Declare a parameterized constructor with two parameters such as 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, 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 refers to the data field of the 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 the instance variables of the class, we have to use the keyword this.

Note: If the local variables(formal arguments) and instance variables are different, there is no need to use the keyword 'this'. For more detail, read out Constructor in Java.  

Calling current class methods using this keyword in Java


The keyword 'this' can be used to call the method of the current class. If you do not write 'this' keyword, the compiler automatically adds 'this' keyword while invoking the method. The following example shows how to add 'this' keyword automatically by the compiler while calling the method. 
Java this keyword with example
Let's understand a simple practical example program related to it.
Program source code 3:
    package com.thiskeyword; public class Hello { /** * this keyword is used to call current/same class method. */ void m() { System.out.println("Hello Java"); } void n() { m(); //method m() is called. m() is same as this.m(). JVM 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

Method returning this reference


Program source code 4:
    package com.thiskeyword; public class AddTest { // Declare an instance variable num with data type int. int num; // Declare one parameter construction 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 the reference to the current object. return this; } public static void main(String[] args) { // Create an object of the class and pass argument 20 to one parameter 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 incr() method. This is done two times. So, 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


The 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. 
Points to remember:
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. JVM never put automatically this keyword like super.
3. Recursion using 'this' call to the constructor is not allowed in Java. 
Let's see some example programs.

Calling default construction from parameterized construction


Program source code: 5
    package com.thiskeyword; public class ABC { // Declare a default constructor. ABC() { System.out.println("HELLO DEEPAK"); } // Declare a parameterized constructor with parameter x. x is a local variable. ABC(int x) { this(); // Must be the first line in the constructor. // calling default constructor from parameterized constructor. System.out.println("WELCOME INDIA"); } } package com.thiskeyword; public class ABCTest { public static void main(String[] args) { // Create an object of class ABC and pass the value to the parameterized constructor. ABC obj=new ABC(12); } }
    Output: HELLO DEEPAK WELCOME INDIA
In the main method of class ABCTest, when an object is created for class ABC with passing an argument 12, it calls the parameterized constructor of class ABC. The keyword this in the first line of the constructor will call the default constructor of class ABC and prints the output "HELLO DEEPAK" 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


Program source code 6:
    package com.thiskeyword; public class CD { CD() { this(5); //Calling parameterized constructor from default constructor. System.out.println("HELLO DEEPAK"); } CD(int x) { System.out.println(x); System.out.println("YOU ARE SO SWEET"); } } package com.thiskeyword; public class CDclasstest { public static void main(String[] args) { CD cd=new CD(); } }
    Output: 5 YOU ARE SO SWEET HELLO DEEPAK

Passing this keyword as an argument in the method


The keyword 'this' in Java can be used to pass as an argument in the method. It is mainly used in the event handling. Let's see a simple example program to understand the concept.
Program source code 7:
    package com.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 an argument in the constructor call


You can also pass this keyword in the constructor call. This concept is useful when you have to use one object in multiple classes. Let's take one simple example program.
Program source code 8:
    package com.thiskeyword; public class A { B obj; // Declare a parameterized constructor whose parameter is obj with 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); } } package com.thiskeyword; public class B { // Declare an instance variable with initialization the value equal to 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 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) { 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 the method must be the class type (non-primitive). 
The following syntax can be used as a returned statement:
Syntax:
   return_type method_name() {
        return this;
   }
Program source code 9:
    package com.thiskeyword; public class Animal { // Declare an instance method show with return type Animal (class type). Animal show(){ return this; } void msg(){ System.out.println("Lion is an animal"); } public static void main(String[] args) { new Animal().show().msg(); } }
    Output: Lion is an animal
Program source code 10: 
In this example program, we will prove that the keyword 'this' refers to the current class object or not.
    package com.thiskeyword; public class Hi { void msg(){ System.out.println(this); // It will print the same reference ID. } public static void main(String[] args) { Hi h=new Hi(); System.out.println(h); // It will print the reference ID. h.msg(); } }
    Output: com.thiskeyword.Hi@1db9742 com.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.

Difference between this and super keyword in Java


The difference between this and super keyword in Java are as follows:
SN 'this' keyword 'super' keyword
1. "this" is a reference variable which contains current class objects. "super" is a reference variable which contains immediate super class objects.
2. Any member of the current class object from within an instance method or a constructor can be referred by using this keyword. If the method overrides one of its super class's method, the overridden method can be called through the use of super keyword.
3. 'this' keyword is used to call another constructor from within a constructor in the same class. 'super' keyword is used to call the super class's constructor from within a constructor of the subclass.
4. JVM never put automatically this() keyword like super() in Java. By default JVM automatically put the super() keyword at first line inside the constructor.


Final words 
Hope that this article has covered almost all important topics related to this keyword in Java. Uses and their practical example programs are very important for freshers. We hope that you have enjoyed the article.
Thanks for reading! 

⏪ Prev Next ⏩