问题
For example, in the following code:
private int id;
public void setID(int ID) {
this.id = ID;
}
public void getID() {
return id;
}
Why don't we say return this.id
in the getter function or conversely say id = ID
in the setter function? Also is this
actually necessary? I mean, aren't the functions called through an object, say obj.setid(1)
or obj.getid()
? Will it work differently if I don't use the this
keyword?
回答1:
You need to use this
when the variable names are the same. It is to distinguish between them.
public void setID(int id) {
this.id = id;
}
The following will still work when this
is removed. It is because their names are not the same.
public void setID(int ID) {
id = ID;
}
回答2:
NO, we use it in both just in case the name of your attributes is same, your example not provide this case, so consider you have this :
private int id;
public void setID(int id) {
// ^^---------This instead of ID
this.id = id;//<<------------So to make a difference between the attribute of method
//and the id declared in the class we use this
}
public void getID() {
return this.id;//<<<---------you can use this.id also here it is not forbidden
}
回答3:
We usually do this to avoid DataShadowing Because if you do below thing in setter (assuming your method parameter name is id instead of ID
public void setID(int id) {
id = id; // You are reassigning the value to the same variable
}
whereas if you want to set the value in Instance level variable then you must use this keyword (which represent the current object)
Note: In your case this is not required as local and the instance level variable name is different.
Hope this clears your confusion
回答4:
When you have define a class and an object of that class,you need this to initialize in setter if the passed argument name and the attribute name of the object are same.
public void setID(int id) {
this.id = id;
}
Basically this refers to the object through which the call is made.
来源:https://stackoverflow.com/questions/43843346/why-do-we-use-this-in-setter-method-but-not-in-getter-method