Difference between this and this() in Java with Example

Difference between this and this() in Java with Example

In Java, both this and this() are entirely different with different functionalities.

Functionalities (Purposes)

  1. this keyword is used to refer always current object
  2. this() is used to access one constructor from another where both constructors belong to the same class

Following table illustrates the differences.

this keyword this()
Used with objects only Used with constructors only
Refers current object Refers a constructor with matching parameters
One of the uses is differentiate between local and instance variables in a method call Used to call one constructor from another belonging to the same class

With the both, inheritance is not involved; everything happens within the same class.

Example Program for this keyword

this and this()
Output screenshot on this and this()

this.num = num;

Whole story lies here only. If this keyword is removed (like num = num), the output is 0. Try and see practically. Why it is 0 if this does not exist? If this is removed, as in num = num, both num are treated as local variables. That is, a local variable is assigned to itself. The value 8 is not reaching the instance variable. If not reached the default value is 0. For this reason, n1.num prints 0. If this exists as in this.num = num, this.num refers the instance variable and num refers the local variable. Here with this presence, the local variable num (with value 8) is assigned instance variable num.

Example Program for this() using constructor overloading

this and this()
Output screen on this and this()

In the above code, constructor is overloaded three times. Using this(), with one object creation, all the three constructors can be called. In the main() method, Officer object o1 is created that calls III constructor. From III, using this(), the I constructor is called and similarly from I, using this("Kejri"), the matching string parameter II constructor is called. That is, order of calling is III, I and II. The output is in reverse order of II, I and III.

Coding Trap: Call to this() must be the first statement in the constructor; else it is compilation error. Thereby, in one constructor do not use two this() statements.

Note: With constructors, we should use the word access and not the word call. Call should be used with methods. But everyone uses call with constructors. For this reason, I am also using call.

3 thoughts on “Difference between this and this() in Java with Example

Leave a Reply

Your email address will not be published. Required fields are marked *