Why should "this.x = x" be used when "return x" is allowed?

I have a little misunderstanding with the tutorial. Here is a snippet from it:

public class Test {
  private int id;

  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
}

      

Anyway, I can't figure out how to access the id. For example, I see that in the getId method, I can directly access the previously defined id by simply specifying the return id. But in the setId method, the previously defined identifier is denoted as this.id, and the method parameter is id.

Now, if the get method had "return this.id", I would understand everything. But at the moment I am confused. My guess is that if I were to return the id in the set method, I would get the parameter back and not the class id. So in conclusion, a class id can be activated by typing "id" if there is no parameter passed with the same name? It sounds strange, what am I missing?

+3


source to share


4 answers


In Java, under normal conditions this

inside a class, it is optional. any attribute can be referenced or not this

.

If you have a parameter or local variable with the same name, the ambiguity makes the entry this

mandatory.

This is called "shading". The local variable is said to shade the attribute.



When you write id

, the most reasonable assumption in Java is that you mean the most local reference, which is a parameter name and not an attribute. To override this behavior, you need to clarify what you want to access this.id

, what the attribute means, not a local variable.

Hope this cleared up!

+5


source


this.id = id;

      

The problem is that you also have a local variable with the same name. Because of this, you cannot access the class member directly, as it id

will refer to a local variable. That is why this

it is necessary to access the member variable of the class here.



You can rewrite as shown below by changing the name, and now is this

no longer needed.

public void setId(int locID) {
    id = locID;
}

      

+2


source


You can put this.id in the getId method and it will still work. It actually says the same thing. This will compile and is perfectly correct:

private int id;

public int getId() {
    return this.id;
}
public void setId(int id) {
    this.id = id;
}

      

+1


source


If you created an object from the Test class and you are trying to access this id

for example:

int test;
test=TestObject.id;

      

You will get an error because it id

is private, so you must say

test=TestObject.getid();

      

Now getid()

will return a private for us id

, which we can call because its public method

-3


source







All Articles