+ 1
Getters, setters and "this"
Why is "this" variable needed for setters and not getters?
3 odpowiedzi
+ 8
Setters have an argument to assign to a class variable, and it usually has the same name as it. Getters don't receive any input. Using "this" indicates to use the one in the class, not the argument. Ex:
public void setName(String name) //Argument "name"
{ this.name = name; } //this.name is the class's "name"
If you name the argument something else, you don't have to use "this", because then there's no name conflict. Ex:
public void setName(String value)
{ name = value; } //Different names, no need for "this"
+ 7
just to add to Tamras answer, in the getter you dont have to use .this because it is there implicitly. even if you dont see it. but if you want you can put it and it will work just the same
e.g.
public int getAge() {
return age;
}
is the same as this
public int getAge () {
return this.age;
}
the this keyword means "the object for which you are calling the method"
+ 1
Thank you both for the quick answers