Keyword this in Java

Within an instance method or a constructor, Java this keyword is used as 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 an instance method or a constructor by using the keyword this.

Using this with a Class Field

We use the keyword this when we want to use the class-level variable inside a method or constructor.

Example:

public ClassA {
  int data;

  public void setData(int newData) {
    this.data = newData;
  }
}

As you can see in the example above, we assigned the value of the newData method parameter to the instance variable data.

We didn’t have to use the keyword this, but many developers like to use it in such cases.

Let’s see an example of when we need to use the keyword this:

public ClassB {
  int data;

  public void setData(int data) {
    this.data = data;
  }
}

Here both the method parameter and the instance variable have the same name. In this case, we have to use the keyword because a method parameter shadows the field.

Shadowing → when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. All operations will be applied to the variable inside the scope.

The inner variable will shadow the variable in the outer scope. 

If we don’t use this keyword, the JVM will apply the operation to the local variable.

public ClassC {
  int data;

  public ClassC(int data) { // constructor
    this.data = data;
  }
}


Using this with Constructors

One class can have multiple constructors, and from within one constructor, we can call another.

We can do that by putting this() call as a first statement, and inside the parentheses, we provide the required args.
This is called explicit constructor invocation.

Example:

public class ClassD {
  private int day;
  private int month;
  private int year;
        
  public ClassD() {
    this(29, 12, 2020);
  }
    
  public ClassD(int year) {
    this(0, 0, year);
  }

  public ClassD(int day, int month, int year) {
    this.day = day;
    this.month = month;
    this.year = year;
  }
}


As you can see, the first two constructors call the third one by providing the corresponding parameters.

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

That’s it!

Leave a Reply

Your email address will not be published.