Saturday, August 20, 2022

Java ‘This’ Keyword: Tutorial With Code Examples

 

Java ‘This’ Introduction

The reference ‘this’ is generally termed as ‘this pointer’ as it points to the current object. The ‘this pointer’ is useful when there is some name for the class attributes and parameters. When such a situation arises, the ‘this pointer’ eliminates the confusion as we can access parameters using ‘this’ pointer.

this pointer

In this tutorial, we will discuss the usage of ‘this’ pointer in various situations along with examples.

When To Use ‘this’ In Java?

In Java the term ‘this’ has the following uses:

  • The reference ‘this’ is used to access the class instance variable.
  • You can even pass ‘this’ as an argument in the method call.
  • ‘this’ can also be used to implicitly invoke the current class method.
  • If you want to return the current object from the method, then use ‘this’.
  • If you want to invoke the current class constructor, ‘this’ can be used.
  • The constructor can also have ‘this’ as an argument.

Let us now look into each of these uses separately.

Access Instance Variable Using ‘this’

Instance variables of class and method parameters may have the same name. ‘this’ pointer can be used to remove the ambiguity that arises out of this.

The Java program below demonstrates how ‘this’ can be used to access instance variables.

class this_Test
{
     int val1;
     int val2;
 
    // Parameterized constructor
    this_Test(int val1, int val2)
    {
        this.val1 = val1 + val1;
        this.val2 = val2 + val2;
    }
 
   void display()
    {
          System.out.println("Value val1 = " + val1 + " Value val2 = " + val2);
    }
}
 
class Main{
 
       public static void main(String[] args)
       {
            this_Test object = new this_Test(5,10);
            object.display();
       }
}

Output:

Access instance variable using ‘this’ Output

In the above program, you can see that the instance variables and method parameters share the same names. We use ‘this’ pointer with instance variables to differentiate between the instance variables and method parameters.

‘this’ Passed As The Method Parameter

You can also pass this pointer as a method parameter. Passing this pointer as a method parameter is usually required when you are dealing with events. For Example, suppose you want to trigger some event on the current object/handle, then you need to trigger it using this pointer.

Given below is a programming exhibit wherein we have passed this pointer to the method.

class Test_method
{
    int val1;
    int val2;
 
    Test_method()
    {
        val1 = 10;
        val2 = 20;
    }
 
    void printVal(Test_method obj)
    {
             System.out.println("val1 = " + obj.val1 + "  val2 = " + obj.val2);
    }
 
    void get()
    {
           printVal(this);
    }
}
 
class Main{
    public static void main(String[] args)
    {
        Test_method object = new Test_method();
        object.get();
    }
}

Output:

‘this’ passed as the method parameter OutPut

In this program, we create an object of the class Test_method in the main function and then call get() method with this object. Inside the get () method, ‘this’ pointer is passed to the printVal () method that displays the current instance variables.

Invoke The Current Class Method With ‘this’

Just as you can pass ‘this’ pointer to the method, you can also use this pointer to invoke a method. If at all you forget to include this pointer while invoking the method of the current class, then the compiler adds it for you.

An example of invoking the class method with ‘this’ is given below.

class Test_this {
 
    void print()
    {
        // calling fuctionshow()
       this.show();
 
       System.out.println("Test_this:: print");
    }
 
    void show() {
        System.out.println("Test_this::show");
    }
}
 
class Main{   
    public static void main(String args[]) {
        Test_this t1 = new Test_this();
        t1.print();
    }
}

Output:Invoke the current class method with ‘this’ output

In this program, the class method print () calls the show() method using this pointer when it is invoked by the class object in the main function.

Return With ‘this’

If the return type of the method is the object of the current class, then you can conveniently return ‘this’ pointer. In other words, you can return the current object from a method using ‘this’ pointer.

Given below is the implementation of returning an object using ‘this’ pointer.

class Test_this
{
   int val_a;
   int val_b;
 
    //Default constructor
   Test_this()
    {
        val_a = 10;
        val_b = 20;
    }
 
   Test_this get()
    {
        return this;
    }
 
   void display()
    {
         System.out.println("val_a = " + val_a + "  val_b = " + val_b);
    }
}
 
class Main{
    public static void main(String[] args)
    {
        Test_this object = new Test_this();
        object.get().display();
    }
}

Output:

Return with this output

The above program shows the method get () that returns this which is an object of class Test_this. Using the current object returned by the get() method, the method display is in turn called.

Using ‘this’ To Invoke The Current Class Constructor

You can also use ‘this’ pointer to invoke the constructor of the current cla.ss. The basic idea is to reuse the constructor. Again if you have more than one constructor in your class, then you can call these constructors from one another resulting in constructor chaining.

Consider the following Java program.

class This_construct
{
     int val1;
     int val2;
 
    //Default constructor
    This_construct()
    {  
        this(10, 20);
        System.out.println("Default constructor \n");
    }
 
    //Parameterized constructor
   This_construct(int val1, int val2)
    {
        this.val1 = val1;
        this.val2 = val2;
        System.out.println("Parameterized constructor");
    }
}
 
class Main{
    public static void main(String[] args)
    {
         This_construct object = new This_construct();
    }
}

Output:

Using this to invoke the current class constructor Output

In the above program, we have two constructors in the class. We call the other constructor using ‘this’ pointer, from the default constructor of the class.

Using ‘this’ As The Argument To Constructor

You can also pass ‘this’ pointer as an argument to a constructor. This is more helpful when you have multiple classes as shown in the following implementation.

class Static_A
{
     Static_B obj;
 
     Static_A(Static_B obj)
    {
        this.obj = obj;
 
        obj.display();
    }
 }
 
class Static_B
{
    int x = 10;
 
    Static_B()
    {
          Static_A obj = new Static_A(this);
    }
 
    void display()
    {
          System.out.println("B::x = " + x);
    }
}
 
class Main{
     public static void main(String[] args) {
        Static_B obj = new Static_B();
    }
}

Output:

Using this as the argument to constructor Output

As shown in the above implementation, we have two classes and each class constructor calls the other class’s constructor. ‘this’ pointer is used for this purpose.


Frequently Asked Questions

Q #1) What is the difference between this and this () in Java?

Answer: In Java, this refers to the current object while this () refers to the constructor with matching parameters. The keyword ‘this’ works only with objects. The call “this ()’ is used to call more than one constructor from the same class.

Q #2) Is this keyword necessary in Java?

Answer: It is necessary especially when you need to pass the current object from one method to another, or between the constructors or simply use the current object for other operations.

Q #3) What is the difference between this () and super () in Java?

Answer: Both this () and super () are keywords in Java. While this () represents the constructor of the current object with matching parameters, super () represents the constructor of the parent class.

Q #4) Can you use both this () and super () in a constructor?

Answer: Yes, you can use it. The constructor this () will point to the current constructor while super () will point to the parent class constructor. Remember that both this () and super () should be the first statement.

No comments:

Post a Comment

Programming in Java (Semester-5)

  Programming in Java (Semester-5) Syllabus Unit I Unit II Unit III Practical Question Bank Java Practical Programs Java Important Topics Qu...