7

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 :)

user207421
  • 305,947
  • 44
  • 307
  • 483
user14044
  • 71
  • 1
  • 2

4 Answers4

6

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.

When you need this?

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.

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.:

public int getBar() {
    return this.bar;
    // return bar;  // <-- this is correct, too
}
gaborsch
  • 15,408
  • 6
  • 37
  • 48
  • 2
    +1 for making including "Readability". I think code readability can't be stressed enough. In the example (a simple accessor method) it's probably overkill, but there are many situations where it does vastly improve readability. – GreyBeardedGeek May 01 '13 at 01:56
  • IMO `return this.bar;` is less readable than `return bar;`. It's just more clutter. – Steve Kuo May 01 '13 at 02:00
  • Agreed @SteveKuo, you should let the IDE take care of differentiating between local variables and class attributes by means of colour schemes, rather than EACH TIME putting the `this.` keyword there manually without actual use other than adding verbosity. @GreyBeardedGeek: do you use notepad or a _proper_ IDE for development? ;-) – klaar Oct 21 '15 at 07:32
  • @klaar Every developer prefers his/her own style of code. In this answer I just stated that many developers use `this` in this manner. Also, most code generators I use in different IDEs produce similar code (by prefixing the instance property). So, this is a common practice, but obvoiusly it does not match everyone's flavour. – gaborsch Oct 21 '15 at 13:17
  • Of course it's a personal preference, but it's a silly one just like putting completely obvious comments above each line of code, telling you exactly the same as what you can deduct from reading the code itself. Indeed, a personal preference and not 'wrong' per se, but it's not the cleverest choice imo. And as a last defence: I was just expressing my anger at people who do this using logical arguments. So glad that I found similar opinions! – klaar Oct 21 '15 at 13:22
4

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

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int a, int b) {
        x = a;
        y = b;
    }
}

but it could have been written like this:

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
user278064
  • 9,982
  • 1
  • 33
  • 46
1

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 function setA():

public void setA(int a)
{
    this.a = a;
}

Since both the data member and the papameter of the method is named a, to refer to the data member, you have to use this.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.

tianz
  • 2,155
  • 2
  • 19
  • 28
0

this refer to the instance of the class itself. Example:

private String name, car;

public class Car(String name, String color)
{
    this.name = name;
    this.color = color;
}
Zach Latta
  • 3,251
  • 5
  • 26
  • 40