[英]Setting instance variable with same name as method parameter?
If I have code like this: 如果我有这样的代码:
public class Foo {
public int bar;
public void setBar(int bar) {
bar = bar;
}
}
Eclipse warns me that the assignment doesn't do anything (for obvious reasons). Eclipse警告我,该分配不会执行任何操作(出于明显的原因)。 Can I fix it by changing it to
this.bar = bar;
我可以通过将其更改为
this.bar = bar;
来修复它吗this.bar = bar;
or is it best to just use a different variable name? 还是最好只使用一个不同的变量名?
Using this.bar = bar;
使用
this.bar = bar;
is just fine. 很好 Most setters are coded this way.
大多数二传手都是这样编码的。
When you need to do something like that, one common course of action is to rename the function parameter. 当您需要执行类似操作时,一种常见的做法是重命名function参数。
public void setBar(int theBar) {
bar = theBar;
}
If you would rather not do that, use this.
如果您不想这样做,请使用
this.
prefix, like this: 前缀,像这样:
this.bar = bar;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.