I have a little misunderstanding with a tutorial. Here is a cut from it:
public class Test {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Anyway the thing i cant understand is how to refer to id. For example i can see that in getId method i can directly acces previously defined id by just saying return id. But in setId method previously defined id is refered to as this.id and method parameter is id.
Now if there would be “return this.id” in get method then i would understand everything. But at the moment i am confuzed. I assume that if i would return id in set method i would get the parameter back, not the class defined id.
So in conclusion, class defined id can be acceced by just typing “id” unless there is a parameter passed with the same name? That sounds kind of strange, what am i missing?
In Java, in normal conditions the
thisinside of a class is optional. any attribute can be refered with or without thethis.When you have a parameter or a local variable with the same name, the ambiguity makes writing the
this, compulsory.This is called “shadowing“. It is said that the local variable is shadowing the attribute.
When you write
id, the most reasonable guess for Java is that you mean the most local reference, which is the parameter name rather than the attribute. To override this behavior, you have to clarify that you are willing to accessthis.id, meaning the attribute, not the local variable.Hope that cleared things out!