Could you tell me why programmers use this.variable ex. (this.miles) in constructor, and what is the advantage of using it?

"this" refers to the object wihch is running the method. If you have a local (method) variable shadowing an instance field, you can refer to the instance field by this.variable .

In a constructor, we commonly use parameters to set fields of the object we are creating. It is convenient to give those parameters the same name as the field they will be passed to, for clarity of code. Since the parameter is a local variable, if it has the same name as a field, it will shadow that field. Therefore, it is necessary to use a "this" reference to tell the compiler that you mean the field, and not the local variable.

This doesn't work:

public class Person{
  private String name;
  public Person(String name)
  {
     name = name;  //local variable is being set to itself, vanishes on completion of this method
  }

  public String toString()
  {
    System.out.println(name);  //oops, name hasn't been set!
  }
}

This works, but the parameter list is not clear:

public class Person{
  private String name;
  public Person(String n)
  {
     name = n;  //local variable is being set to itself, vanishes on completion of this method
  }

  public String toString()
  {
    System.out.println(name);  //name has been set, but what's an "n"?
  }
}

This works:

public class Person{
  private String name;
  public Person(String name)
  {
     this.name = name;  //local variable is being set to itself, vanishes on completion of this method
  }

  public String toString()
  {
    System.out.println(name);  //now it works!
  }
}
commented: Nice explanation. +14
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.