ATTN AP Computer Science Lovers... An easy question about the "this" command!

<p>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.</p>

<p>For example, if we look at #4 here: <a href="http://apcentral.collegeboard.com/apc/public/repository/ap_frq_computerscience_12.pdf%5B/url%5D"&gt;http://apcentral.collegeboard.com/apc/public/repository/ap_frq_computerscience_12.pdf&lt;/a&gt;&lt;/p>

<p>And we look at the solutions here: <a href="http://apcentral.collegeboard.com/apc/public/repository/ap12_computer_science_a_q4.pdf%5B/url%5D"&gt;http://apcentral.collegeboard.com/apc/public/repository/ap12_computer_science_a_q4.pdf&lt;/a&gt;&lt;/p>

<p>We see that one solution to part a) is</p>

<p>public int countWhitePixels() {
int whitePixelCount = 0;
for (int[] row : this.pixelValues) {
for (int pv : row) {
if (pv == this.WHITE) {
whitePixelCount++;
}
}
}
return whitePixelCount;
}
while another solution is</p>

<p>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;
} </p>

<p>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?</p>

<p>Thank you SO much for your help :)</p>

<p>You are correct, it is not necessary. There doesn’t really seem to be a reason why they did that.</p>

<p>The only times you need to use this are the following:

  1. when overloading a constructor
  2. when you have a field and an instance variable with the same name
    example:
    public class Foo {</p>

<p>private int bar;</p>

<p>public Foo() {
this(0);
}</p>

<p>public Foo(int bar) {
this.bar = bar;
}</p>

<p>}</p>