This


This

This keyword is used for referring to the current object inside a method or a constructor

A common usage of this keyword in java eliminates the confusion between the parameters and the class attributes using the same name. However, the keyword also has some other critical usages, including:

  • It can be used to refer to the current class’s instance variable.
  • It is used to invoke current class’s method implicitly.
  • It can be used to pass as an argument in the method call.
  • this() also helps invoke the current class’s constructor.
  • It can also be used to return the current class’s instance from the given method.
  • It passes as the argument for calling the constructor.

Difference between this() and this in Java:

In java language, this() refers to the constructor, and this refers to the current object of the current class. Thus, this keyword only works with objects, whereas this() call is used to call more than one constructor from the same class.

Difference between super() and this() in Java:

In java, both super() and this() are the keywords. In programming, super() is used to represent the parent class’s constructor, whereas this() is used to represent the current object’s constructor using the matching parameters.

Example:

Com.knowledge2life public class Main { String x; // Constructor with a parameter public Main(String x) { this.x = x; } // Call the constructor public static void main(String[] args) { Main myObj = new Main("Knowledge2life"); System.out.println("Value of x = " + myObj.x); } }

OUTPUT:

: Value of x = Knowledge2life