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.
For example, if we look at #4 here: http://apcentral.collegeboard.com/apc/public/repository/ap_frq_computerscience_12.pdf
And we look at the solutions here: http://apcentral.collegeboard.com/apc/public/repository/ap12_computer_science_a_q4.pdf
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;
}
while another solution is
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;
}
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?
Thank you SO much for your help :)
When the name of a method parameter is the same as one of your class data member; then, to refer to the data member, you have to put
this.
before it. For example, in the functionsetA()
:Since both the data member and the papameter of the method is named
a
, to refer to the data member, you have to usethis.a
. In other cases, it's not required.And, in your case, I don't think it's necessary to use the
this
, though there is no harm to use it.From The Java™ Tutorials
Using this with a Field
The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
For example, the Point class was written like this
but it could have been written like this:
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 instatic
methods or class initializer blocks.When you need this?
Only in cases when a same-named variable (local variable or method parameter) is hiding the declaration. For example:
Here the method parameter is hiding the instance property.
When coders used to use it?
To improve readability, it is a common practice that the programmers prepend the
this.
qualifier before accessing an instance property. E.g.:this
refer to the instance of the class itself. Example: