Saturday 7 February 2015

Java "this" Prefix

If you have a class and a constructor method with parameter(s), you might want to use the same names for the variables in the class as you use for the parameters passed to the method. To distinguish between the two, you can prefix the variables belonging to the class with the word this. In the example below, I create a class called Square. It has a variable called width. The constructor method accepts a parameter with the same name. It then displays the value of the parameter and the initial value of the class variable. After that, it assigns the parameter value to the class variable and redisplays the class variable to show that the assignment has worked: 

Java > cat Square.java
class Square
  {
  double width;
  Square (double width)
    {
    System.out.println("width = " + width);
    System.out.println("this.width = " + this.width);
    System.out.println("Assigning parameter value");
    this.width = width;
    System.out.println("this.width = " + this.width);
    }
  }
Java > javac Square.java
Java > cat SquareExample.java
public class SquareExample
  {
  public static void main(String args[])
    {
    Square s1 = new Square(5);
    }
  }
Java > javac SquareExample.java
Java > java SquareExample
width = 5.0
this.width = 0.0
Assigning parameter value
this.width = 5.0
Java >