为什么我们在setter方法中使用'this'而不在getter方法中使用? [英] Why do we use 'this' in setter method but not in getter method?
问题描述
例如,在以下代码中:
private int id;
public void setID(int ID) {
this.id = ID;
}
public void getID() {
return id;
}
我们为什么不在getter函数中说return this.id
或相反在setter函数中说id = ID
?还有this
实际必要吗?我的意思是,不是通过对象(例如obj.setid(1)
或obj.getid()
)调用函数吗?如果我不使用this
关键字,它会以不同的方式工作吗?
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?
推荐答案
当变量名相同时,您需要使用this
.是要区分它们.
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;
}
当删除this
时,以下内容仍将起作用.这是因为它们的名称不同.
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;
}
这篇关于为什么我们在setter方法中使用'this'而不在getter方法中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!