Core JAVA

this keyword in Java

There can be a lot of usage of this keyword. In java, this is a reference variable that refers to the current object. Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

Usage of this keyword
Here is given the 6 usage of this keyword.

  1. this keyword can be used to refer current class instance variable.
  2. this() can be used to invoke current class constructor.
  3. this keyword can be used to invoke current class method (implicitly)
  4. this can be passed as an argument in the method call.
  5. this can be passed as argument in the constructor call.
  6. this keyword can also be used to return the current class instance.

Using this with a Field

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

For example, the Point class was written like this

public class Point {
    public int x ;
    public int y ;
        
    //constructor
    public Point(int x, int y) {
        x = x;
        y = y;
    }
   void display(){
      System.out.println(x+" :: "+y);
   }
   public static void main(String args[]){
    Point s1 = new Point (111,222);
    Point s2 = new Point (333,444);
    s1.display();
    s2.display();
    }
}

output:
0 :: 0
0 :: 0

In the above example, parameter (formal arguments) and instance variables are same that is why we are using this keyword to distinguish between local variable and instance variable.

but it could have been written like this:

public class Point {
    public int x = 0;
    public int y = 0;
        
    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
   void display(){
      System.out.println(x+" :: "+y);
   }
   public static void main(String args[]){
    Point s1 = new Point (111,222);
    Point s2 = new Point (333,444);
    s1.display();
    s2.display();
    }
}

output:
111 :: 222
333 :: 444

Using this with a Constructor

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here’s another Rectangle class, with a different implementation from the one in the Objects section.

public class Rectangle {
    private int x, y;
    private int width, height;
        
    public Rectangle() {
        this(0, 0, 0, 0);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}

This class contains a set of constructors. Each constructor initializes some or all of the rectangle’s member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. As before, the compiler determines which constructor to call, based on the number and the type of arguments.

If present, the invocation of another constructor must be the first line in the constructor.

Where to use this() constructor call?
The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let’s see the example given below that displays the actual use of this keyword.

class Employee{
    int id;
    String name;
    String city;
    
    Employee(int id,String name){
    this.id = id;
    this.name = name;
    }
    Employee(int id,String name,String city){
    this(id,name);//now no need to initialize id and name
    this.city=city;
    }
    void display(){
     System.out.println(id+" "+name+" "+city);
    }
    
    public static void main(String args[]){
    Employee e1 = new Employee(222,"Dinesh");
    Employee e2 = new Employee(555,"Anamika","Noida");
    e1.display();
    e2.display();
   }
}

Output:
222 Dinesh null
555 Anamika Noida


Note: Call to this() must be the first statement.

class Employee{
    int id;
    String name;
    Employee(){
     System.out.println("default constructor is invoked");
    }
    
    Employee(int id,String name){
    id = id;
    name = name;
    this ();//must be the first statement
    }
    void display(){
     System.out.println(id+" "+name);
   }
    
    public static void main(String args[]){
    Employee e1 = new Employee(222,"Dinesh");
    Employee e2 = new Employee(555,"Anamika");
    e1.display();
    e2.display();
   }
}
Output:
Compile Time Error

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago