何时使用“this"在 Java 中 [英] When to use "this" in Java

查看:18
本文介绍了何时使用“this"在 Java 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的琐碎且可能很愚蠢的问题道歉,但我对在使用方法或访问某些内容时何时使用this"前缀感到有些困惑.

I apologize for my trivial and probably silly question, but I am a bit confused as to when to use the "this" prefix when using a method or accessing something.

例如,如果我们看#4这里:http://apcentral.collegeboard.com/apc/public/repository/ap_frq_computerscience_12.pdf

For example, if we look at #4 here: 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

And we look at the solutions here: http://apcentral.collegeboard.com/apc/public/repository/ap12_computer_science_a_q4.pdf

我们看到 a) 部分的一个解决方案是

We see that one solution to part a) is

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 时的前缀,但在第二个解决方案中没有?我认为这个"是隐含的,所以我说这个"是正确的.第一个解决方案根本不需要吗?

Here is my question. Why is it that they use the "this." prefix when accessing pixelValues and even WHITE in the first solution, but not in the second? I thought "this" was implicit, so am I correct in saying "this." is NOT necessary at all for the first solution?

非常感谢您的帮助:)

推荐答案

使用 this,您可以明确引用您所在的对象实例.您只能在实例方法或初始化块中执行此操作,但不能在 static 方法或类初始化块中执行此操作.

With this, you explicitly refer to the object instance where you are. You can only do it in instance methods or initializer blocks, but you cannot do this in static methods or class initializer blocks.

什么时候需要?

仅在同名变量(局部变量或方法参数)隐藏声明的情况下.例如:

Only in cases when a same-named variable (local variable or method parameter) is hiding the declaration. For example:

private int bar;
public void setBar(int bar) {
    this.bar = bar;
}

这里的方法参数隐藏了实例属性.

Here the method parameter is hiding the instance property.

程序员什么时候用过?

为了提高可读性,程序员在访问实例属性之前添加 this. 限定符是一种常见的做法.例如:

To improve readability, it is a common practice that the programmers prepend the this. qualifier before accessing an instance property. E.g.:

public int getBar() {
    return this.bar;
    // return bar;  // <-- this is correct, too
}

这篇关于何时使用“this"在 Java 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆