引用私有变量时,需要this.variableName声明吗?
When referencing a private variable, do you need the this.variableName declaration?
public class sample {
private int x = 3;
public sample() {}
public sample(int num) {
this();
x = num;
}
public int getX() {
// should I use return this.x; or just return x;? Does it matter which one?
}
}
我用过 return x;到目前为止我的代码中的样式,我想知道是否使用 return this.x;提供任何好处,或者纯粹是为了 readability/clarity。抱歉,如果这看起来含糊不清或令人困惑,我真的不知道该怎么说。
考虑 setX(int x)
,为了消除参数 x
和字段 x
之间的歧义,您需要编写类似
的内容
public void setX(int x) {
this.x = x;
}
否则(如果x
不是shadowed),则不需要指定this
(它是implicit ).
public int getX() {
return x; // <-- same as return this.x;
}
没有。您应该只能使用 return x;
。你应该在技术上使用 this.x
的唯一原因是如果你在方法中有一个局部变量 x
。
public class sample {
private int x = 3;
public sample() {}
public sample(int num) {
this();
x = num;
}
public int getX() {
// should I use return this.x; or just return x;? Does it matter which one?
}
}
我用过 return x;到目前为止我的代码中的样式,我想知道是否使用 return this.x;提供任何好处,或者纯粹是为了 readability/clarity。抱歉,如果这看起来含糊不清或令人困惑,我真的不知道该怎么说。
考虑 setX(int x)
,为了消除参数 x
和字段 x
之间的歧义,您需要编写类似
public void setX(int x) {
this.x = x;
}
否则(如果x
不是shadowed),则不需要指定this
(它是implicit ).
public int getX() {
return x; // <-- same as return this.x;
}
没有。您应该只能使用 return x;
。你应该在技术上使用 this.x
的唯一原因是如果你在方法中有一个局部变量 x
。