Java this Keyword

Java "this" Keyword

In Java, the this keyword is a reference variable that refers to the current object. It is a way for an object to refer to itself.

One of its most common uses is to eliminate the confusion between class attributes and parameters with the same name.


Disambiguation of Variables

When you have a constructor (or any method) where the parameter names are the same as the class's attribute names, this is used to distinguish them.

Using `this` to Disambiguate

public class Car {
  String modelName;
  int modelYear;

// The parameter 'modelName' has the same name as the attribute. public Car(String modelName, int modelYear) { // this.modelName is the attribute // modelName is the parameter this.modelName = modelName; this.modelYear = modelYear; }

public static void main(String[] args) { Car myCar = new Car("Mustang", 1969); System.out.println("Model: " + myCar.modelName + ", Year: " + myCar.modelYear); } }

If you did not use this in the example above, the compiler would be confused. Writing modelName = modelName; would simply assign the parameter's value to itself, leaving the class attribute unchanged.


Other Uses of this

The this keyword has other advanced uses as well:

Using this is a standard convention and makes your code much clearer and less error-prone, especially in complex classes.