Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The use of "this" in Java

If I write the following class:

public class Example {

      int j;
      int k;

      public Example(int j, int k) {
           j = j;
           k = k;
      }

      public static void main(String[] args) {
           Example exm = new Example(1,2);
           System.out.println(exm.j);
           System.out.println(exm.k);
      }

}

The program compiles, but when I run the program, the main method will print out two 0s. I know that in order to say that I want to initialize the instance variables in the constructor I have to write:

this.j = j;
this.k = k;

But if I don't write it, then which variable is evaluated (or considered) in the constructor (on the left and on the write hand side of the expressions)? Is is the argument or the instance variable? Does it make a difference?

Are there other cases where the use of this is obligatory?

like image 580
user42155 Avatar asked Feb 05 '09 15:02

user42155


2 Answers

If you don't write "this.variable" in your constructor, and if you have a local variable (including the function parameter) with the same name as your field variable in the constructor, then the local variable will be considered; the local variable shadows the field (aka class variable).

One place where "this" is the only way to go:

class OuterClass {
  int field;

  class InnerClass {
    int field;

    void modifyOuterClassField()
    {
      this.field = 10; // Modifies the field variable of "InnerClass"
      OuterClass.this.field = 20; // Modifies the field variable of "OuterClass",
                                  // and this weird syntax is the only way.
    }
  }
}
like image 51
Srikanth Avatar answered Oct 01 '22 05:10

Srikanth


If you say just j in your constructor then the compiler will think you mean the argument in both cases. So

j = j;

simply assigns the value of the argument j to the argument j (which is a pretty pointless, but nonetheless valid statement).

So to disambiguate this you can prefix this. to make clear that you mean the member variable with the same name.

The other use of this is when you need to pass a reference to the current object to some method, such as this:

someObject.addEventListener(this);

In this example you need to refer to the current object as a whole (instead of just a member of the object).

like image 29
Joachim Sauer Avatar answered Oct 01 '22 05:10

Joachim Sauer