next up previous
Next: Constructors Up: Unit 03 Previous: The implicit formal parameter

Use of this

Typically, this is used when there is a local variable (or a formal parameter) declared inside the method with the same name as an instance variable, and we want to distinguish between the instance variable and the local variable. Indeed, if we declare a local variable using the same identifier as for an instance variable, then the name of the local variable hides the name of the instance variable, and we need to explicitly use this to denote the instance variable (the implicit use of this is blocked).

Example:

public class Person {
  private String name;
  private String residence;

  public String getName() {
    return name;
  }
  public String getResidence() {
    String residence;
       // the local variable masks the instance variable with the same name
    residence = this.residence;
       // this is used to distinguish the instance var from the local var
    return residence;
       // here we are referring to the local variable
  }
  public void setResidence(String residence) {
    this.residence = residence;
       // this is again used to distinguish the instance var from the local var
  }
}


next up previous
Next: Constructors Up: Unit 03 Previous: The implicit formal parameter