Home > Net >  This keyword Java name similiar to parameter variable name
This keyword Java name similiar to parameter variable name

Time:09-21

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 parameter variable names similar to instance variable names?(ie) 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

CodePudding user response:

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.

  •  Tags:  
  • java
  • Related