DEV Community

Cover image for  Mastering 'this' keyword in Java.
Sai Laasya Vabilisetty
Sai Laasya Vabilisetty

Posted on • Edited on • Originally published at laasyasettyblog.hashnode.dev

Mastering 'this' keyword in Java.

We mostly use this keyword as a reference to the current object in a method or a constructor. In simple words, it is a reference variable that points to the current object. In the below example, this keyword is used to refer to current class object.

class Example{
int a;
Example(int a){
this.a=a;           
}
public static void main(String args[]){
Example obj=new Example("John Doe");
}
}
Enter fullscreen mode Exit fullscreen mode

But, there are many other cases where we can use this keyword efficiently. Let's explore them now.🤩

1. Using this keyword to eliminate confusion between class and instance variables.

If the variable declared in class and method/constructor share the same name then we use this keyword to refer class instance.

Explanation: As you can see in the below code, we have declared 2 global variables as place and pin, the same variable names are used for constructor parameters too. So, we use this to tell the program that the arguments we pass for the constructor variables are for the global variables too. Therefore, when we try to print pin and place in meth() it prints the values we passed during object creation.

public class Example{
    String place;
    int pin;
    One(String place,int pin){
     this.pin=pin;                  
    this.place=place;
    }
     void meth(){
      System.out.println(place+" "+pin);
    }
    public static void main(String args[]){
      Example obj=new Example("chennai",603103);                                          
       obj.meth();
    }
}

Enter fullscreen mode Exit fullscreen mode
Output: chennai 603103
Enter fullscreen mode Exit fullscreen mode

2. this keyword is used to call other constructors of the same class.

Here, we are using this to invoke a parameterized constructor inside a default constructor.
this_two.PNG

public class Example {
    Two(int a,int b){
    System.out.println("Parameterized Constructor");  
    }
    Two(){
        this(25,32);  
    System.out.println("Default Constructor");    
    }
    public static void main(String args[]){
    Example obj= new Example();   
    }
    }
Enter fullscreen mode Exit fullscreen mode
Output:   Parameterized Constructor
          Default Constructor
Enter fullscreen mode Exit fullscreen mode

3. Constructor Chaining

This is a process of calling one constructor from another constructor of the same class. The idea of this concept is already covered in the previous step, but let's explore it more clearly now.

this_three.PNG

Explanation:To understand clearly I have commented constructors with numbers in the below code. Now, when the object is created, constructor-1 is invoked which leads to constructor-2 as we used this() to call and thereby constructor-2 uses this() to call constructor-3. Therefore, the order of execution will be constructor 3,2 and 1.

public class Example {
 /*1*/ Example(){
        this(10,"laasya");
        System.out.println("Constructor 1");
        }
 /*2*/ Example(int a,String s){
        this(10);
        System.out.println("Constructor 2");
    }
/*3*/ Example(int a){
        System.out.println("Constructor 3");
    }
     public static void main(String args[]){
        new Example();
    }
}
Enter fullscreen mode Exit fullscreen mode
Output: Constructor 3
        Constructor 2
        Constructor 1
Enter fullscreen mode Exit fullscreen mode

4. Using this to invoke the current class method.

Explanation: Here we are using this to call one method from another. Instead of writing this.check() we can simply use check() which works completely fine. But it is recommended to use this as it ensures code readability in long run.

public class Example{
    void check(){
     System.out.println("This method is called from another method");
    }
    void checkTwo(){
        check();
    System.out.println("I called another method");      
    }
    public static void main(String args[]){
    Example obj=new Example();
    obj.checkTwo();
    }
}
Enter fullscreen mode Exit fullscreen mode
output: This method is called from another method
        I called another method
Enter fullscreen mode Exit fullscreen mode

5. Passing this keyword as a method argument

Explanation: In the below example, we have declared methodOne() which has a class object as a parameter. So, while calling methodOne() we can pass this as an argument which prints the value of 'a' which was passed to constructor during object creation.

public class Example {
int a;
Example(int b){
a=b;
}
void methodOne(Example object){
 System.out.println("I was called by using this keyword as arg "+a);
    }
void methodTwo(){
   methodOne(this);
    }
    public static void main(String args[]){
     Example obj= new Example(20);
     obj.methodTwo();
    }
}
Enter fullscreen mode Exit fullscreen mode
Output: I was called by using this keyword as arg 20
Enter fullscreen mode Exit fullscreen mode

6. Using this keyword to return the current class object.

Explanation: In the below code, when meth() method which is defined by class-name is called it returns the current class instance. Remember meth() returns but doesn't print. So, to print values we are using display().

public class Example {
   int age;
   Example(){
     age =20;
   }
    Example meth(){
        return this;
    }
    void display(){
       System.out.println(age);
    }
    public static void main(String args[]){
Example obj=new Example();
obj.meth().display();
    }
}
Enter fullscreen mode Exit fullscreen mode
Output: 20
Enter fullscreen mode Exit fullscreen mode

7. Using this keyword as a constructor argument

Explanation:In this below example, we have 2 classes A and T. When a new object of A is created, the default constructor of A creates a new object of class T passing this as an argument. Now, the default constructor of T stores the details of object A in object T as we did this.obj=obj. Hence, when we call `display()' it gets the value of the variable created in class A and prints it.

 public class A{
     int age=10;
     A(){
         T t=new T(this);
         t.display();
     }
     class T {
      A obj;
       T(A obj){
         this.obj=obj;
       }
       void display(){
           System.out.println(obj.age);
       }
   }
     public static void main(String args[]){
      new A();
    }

 }
Enter fullscreen mode Exit fullscreen mode
Output: 10
Enter fullscreen mode Exit fullscreen mode

That's it😍. You have reached the end of the article.
Happy Java'ing people🤗


Thank you for reading till the end. I would love to connect with you through Twitter, LinkedIn, Github.😍

Top comments (0)