Question about java encapsulation and this keyword

gabogabans :

I come from a PHP background and I'm having trouble understanding encapsulation and more precisely this keyword, in theis example bellow:

public class Person {
  private String name; // private = restricted access

  // Getter
  public String getName() {
    return name;
  }

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

In the getter method why is name returned instead of this.name? afaik this.name refers to the Person object property, why name and not this.name?

Also in the example bellow:

public class Order implements IOrder {

public String uid;
private Map map;

public Order(){}
public Order(String uid){
this.uid=uid;
map = new HashMap();
}

Why is map refered as map instead of this.map, also why is there two(2) constructors instead of one?

Taschi :

"name" and "this.name" are equivalent as long as there isn't a local variable which is also called "name". You can always access class variables without the "this" identifier from instance methods of the same class. The only case in your examples where "this" is actually necessary is in the "uid" example, where a local variable with the same name hides the class variable.

The reason why there are two constructors is just flexibility and convenience. When you want to instantiate Order, you can pick the constructor that fits your needs better.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related