Shr*_*hob 2 java getter setter getter-setter
例如,在以下代码中:
private int id;
public void setID(int ID) {
this.id = ID;
}
public void getID() {
return id;
}
Run Code Online (Sandbox Code Playgroud)
为什么我们不在return this.idgetter函数中说或者反过来说id = ID在setter函数中呢?还有this必要吗?我的意思是,不是通过对象调用的函数,比如说obj.setid(1)或者obj.getid()?如果我不使用this关键字,它会有不同的工作吗?
您需要this在变量名称相同时使用.它是为了区分它们.
public void setID(int id) {
this.id = id;
}
Run Code Online (Sandbox Code Playgroud)
this删除后,以下内容仍然有效.这是因为他们的名字不一样.
public void setID(int ID) {
id = ID;
}
Run Code Online (Sandbox Code Playgroud)
不,我们在这两种情况下都使用它,以防万一您的属性名称相同,而您的示例未提供这种情况,因此请考虑使用此属性:
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3723 次 |
| 最近记录: |