我为我的琐碎且可能愚蠢的问题道歉,但我对在使用方法或访问某些内容时何时使用“this”前缀感到有点困惑。
例如,如果我们看#4
这里:http://apcentral.collegeboard.com/apc/public/repository/ap_frq_computerscience_12.pdf http://apcentral.collegeboard.com/apc/public/repository/ap_frq_computerscience_12.pdf
我们在这里看看解决方案:http://apcentral.collegeboard.com/apc/public/repository/ap12_computer_science_a_q4.pdf http://apcentral.collegeboard.com/apc/public/repository/ap12_computer_science_a_q4.pdf
我们看到 a) 部分的一个解决方案是
public int countWhitePixels() {
int whitePixelCount = 0;
for (int[] row : this.pixelValues) {
for (int pv : row) {
if (pv == this.WHITE) {
whitePixelCount++;
}
}
}
return whitePixelCount;
}
而另一个解决方案是
public int countWhitePixels() {
int whitePixelCount = 0;
for (int row = 0; row < pixelValues.length; row++) {
for (int col = 0; col < pixelValues[0].length; col++) {
if (pixelValues[row][col] == WHITE) {
whitePixelCount++;
}
}
}
return whitePixelCount;
}
这是我的问题。为什么他们用“这个”。在第一个解决方案中访问 PixelValues 甚至 WHITE 时有前缀,但在第二个解决方案中则不然?我认为“这个”是隐含的,所以我说“这个”是正确的。对于第一个解决方案根本没有必要吗?
非常感谢你的帮助 :)
With this
,您明确引用您所在的对象实例。您只能在实例方法或初始化块中执行此操作,但不能在static
方法或类初始化块。
你什么时候需要这个?
仅当存在同名变量(局部变量或方法参数)时hiding声明。例如:
private int bar;
public void setBar(int bar) {
this.bar = bar;
}
这里方法参数隐藏了实例属性。
程序员什么时候使用它?
为了提高可读性,程序员通常会在前面加上this.
访问实例属性之前的限定符。例如。:
public int getBar() {
return this.bar;
// return bar; // <-- this is correct, too
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)