Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use "this" in Java

Tags:

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.

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

like image 717
user14044 Avatar asked May 01 '13 00:05

user14044


2 Answers

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
}
like image 54
gaborsch Avatar answered Sep 21 '22 07:09

gaborsch


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;
    }
}
like image 33
user278064 Avatar answered Sep 22 '22 07:09

user278064