Skip to content
Advertisement

This keyword Java name similiar to parameter variable name

My understanding of the this keyword in java is that you are referencing instance variables as opposed to local variables within a method to save confusion between both names.

As stupid as the question may seem, why would I have a parameter variable names similar to instance variable names? Or exactly the same name… what is the purpose of having similar names?

I’m really just starting out in java so forgive my ignorance

Thanks

Advertisement

Answer

One common use of this feature is when creating a constructor or accessor methods (getter/setter).

public class MyClass {
  private String name;

  public MyClass(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

Note that parameter names are usually part of the publicly-visible API — they are shown in generated Javadocs and by IDE code tools. Therefore, often the “correct” parameter name to show to users of your class are an exact match for the internal fields inside the class.

Additionally, this means not having to come up with unique names for the parameters (or fields) just to avoid having conflicting names for a parameter with a very limited scope.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement