java
  1. java-this-keyword

Java 'this' Keyword

Syntax

this.variableName;
this.methodName();

Example

public class Person {
  private String name;
  
  public Person(String name) {
    this.name = name;
  }
  
  public String getName() {
    return this.name;
  }
}

Output

The getName() method will return the value of the name variable for the given instance of the Person class.

Explanation

In Java, the this keyword is used to refer to the current instance of the class. It is often used to distinguish between instance variables and local variables or method parameters with the same name.

In the example above, the this keyword is used to refer to the name instance variable in the getName() method. This ensures that the method returns the value of the correct name variable for the current instance of the Person class.

The this keyword can also be used to call other methods within the same class. This is useful when you want to call a specific version of a method that is overloaded. By using this.methodName(), you are calling the method on the current instance of the class.

Use

The this keyword is mainly used to avoid ambiguity when referring to instance variables, local variables, and method parameters within the same method.

Additionally, the this keyword can be used to call other methods within the same class. This is useful for calling specific versions of overloaded methods.

Important Points

  • Use the this keyword to refer to the current instance of the class.
  • this.variableName refers to an instance variable.
  • this.methodName() calls another method within the same class.
  • The this keyword is mainly used to avoid ambiguity between instance variables and local variables/method parameters with the same name.

Summary

The this keyword is essential in Java programming because it helps avoid ambiguity between instance variables and local variables/method parameters with the same name. The this keyword is mainly used to refer to the current instance of the class and to call other methods within the same class.

Published on: