tags:

views:

1662

answers:

9

I'm trying to get an understanding of what the the java keyword this actually does. I've been reading Sun's documentation but I'm still fuzzy on what this actually does.

+4  A: 

"this" is a reference to the current object.

See details here

Otávio Décio
+14  A: 

The this keyword is a reference to the current object.

class Foo
{
    private int bar;

    public Foo(int bar)
    {
        // the "this" keyword allows you to specify that
        // you mean "this type" and reference the members
        // of this type - in this instance it is allowing
        // you to disambiguate between the private member
        // "bar" and the parameter "bar" passed into the
        // constructor
        this.bar = bar;
    }
}

Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.

If you were to reference objects that are intrinsically yours you would say something like this:

My arm or my leg

Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:

class Foo
{
    private int bar;

    public Foo(int bar)
    {
        my.bar = bar;
    }
}
Andrew Hare
You could do the above without "this", for example using something like hungarian notation. m_bar = bar. So does not really explain what this is really important for.
ng
could it be to avoid strange constructs like that?
Magnar
@ng: What do you do when you can't rename the field? Like when it's a protected field from a super class?
Aaron Digulla
@ng - You are correct that my usage of "this" could easily be replaced with careful naming conventions. However I believe that I gave the most simple example as it seems clear that the OP is just learning OOP and may have trouble understanding a more advanced usage of "this".
Andrew Hare
@Andrew Very nice explanation.
EricSchaefer
True, but over simplifying the example can be confusing also, making use of "this" to pass the actual object outside the scope of the object itself provides a very clear example of its application and importance.
ng
@Aaron Digulla: Change the parameter, easy...
ng
+3  A: 

An even better use of this

public class Blah implements Foo {

   public Foo getFoo() {
      return this;
   }
}

It allows you to specifically "this" object in the current context. Another example:

public class Blah {

   public void process(Foo foo) { 
      foo.setBar(this);
   }
}

How else could you do these operations.

ng
For your first example: it really makes no sense to return 'this' from an object. The caller already has a reference to your object, how else would he invoke the method?
eljenso
@eljenso: If "return this;" is the only line in the method, then yes, it's pretty useless. But if it's e.g. a setter, it allows you to do method chaining: myFoo.setBar(myBar).setBaz(myBaz).setMyInt(1);
Michael Myers
Not only that but what if returning this is a characteristic of an interface implementation? I challenge you to show me a single complex project that does not need to return this at some point. Its a critical requirement of most OO systems.
ng
@mmyers I agree, I forgot about that one.
eljenso
@ng Every caller invokes getFoo() on a (sub)type of Foo. Why the method if you can do Blah blah = new Blah(); Foo foo = blah; Maybe we can turn things around, and you can show me a project where "this" is returned as you described, so I can better understand what you're trying to say.
eljenso
@eljenso: This goes right to the heart of polymorphism, consider X implementing A and B, I have a reference to A. I call A.getBlah, which returns "this" (being X) the method A.getBlah returns B. I know nothing of the structure of X, not do I care. Take a look at Swing or Wicket for example.
ng
@ng Still makes no sense. If you don't mind I'll turn this into a top-level question and I invite you to answer it in more detail there.
eljenso
http://stackoverflow.com/questions/581722/when-does-it-make-sense-to-return-this-reference
eljenso
@eljenso: Well, I have answered your question, should be obvious what I am talking about.
ng
A: 

The keyword this is a reference to the current object. It's best explained with the following piece of code:

public class MyClass {

    public void testingThis() 
    {
        // You can access the stuff below by 
        // using this (although this is not mandatory)

        System.out.println(this.myInt);
        System.out.println(this.myStringMethod());

        // Will print out:
        // 100
        // Hello World
    }

    int myInt = 100;
    string myStringMethod() 
    {
        return "Hello World";
    }

}

It's not used a lot unless you have code standard at your place telling you to use the this keyword. There is one common use for it, and that's if you follow a code convention where you have parameter names that are the same as your class attributes:

public class ProperExample {
    private int numberOfExamples;

    public ProperExample(int numberOfExamples) 
    {
        this.numberOfExamples = numberOfExamples;
    }
}

One proper use of the this keyword is to chain constructors (making constructing object consistent throughout constructors):

public class Square {
    public Square() 
    {
        this(0, 0);
    }

    public Square(int x_and_y) 
    {
        this(x_and_y, x_and_y);
    }

    public Square(int x, int y)
    {
       // finally do something with x and y
    }
}

This keyword works the same way in e.g. C#.

Spoike
This code is incorrect, a static method has no reference to this.
ng
does it compile ? accessing object elements from a static method should not
chburd
No it doesn't. main() is a static method and so there is no 'this' pointer because there is no object that is invoking it. This should not compile.
James
whoops. I wrote an example in haste. fixing it.
Spoike
This is another poor example of how "this" can be used, and why its fundamentally important to the OO paradigm.
ng
@ng: *sigh* strawman and ad hominem attack arguments, grow up.
Spoike
+1 I really don't understand why this answer was so terrible
Andrew Hare
+1 as well, some people might better check their own "examples".
eljenso
ng
@ng: Within seconds I was downvoted while I was still working on the answer and the only difference with the example I had before was calling from a static main method. Don't get quick with judging people by their answers since the answers can be edited to the better, mine geared towards beginners.
Spoike
+1  A: 

The keyword 'this' refers to the current object's context. In many cases (as Andrew points out), you'll use an explicit this to make it clear that you're referring to the current object.

Also, from 'this and super':

*There are other uses for this. Sometimes, when you are writing an instance method, you need to pass the object that contains the method to a subroutine, as an actual parameter. In that case, you can use this as the actual parameter. For example, if you wanted to print out a string representation of the object, you could say "System.out.println(this);". Or you could assign the value of this to another variable in an assignment statement.

In fact, you can do anything with this that you could do with any other variable, except change its value.*

That site also refers to the related concept of 'super', which may prove to be helpful in understanding how these work with inheritance.

Joe Liversedge
A: 

Think of it in terms of english, "this object" is the object you currently have.

WindowMaker foo = new WindowMaker(this);

For example, you are currently inside a class that extends from the JFrame and you want to pass a reference to the WindowMaker object for the JFrame so it can interact with the JFrame. You can pass a reference to the JFrame, by passing its reference to the object which is called "this".

Kyle G
+10  A: 

The keyword this can mean different things in different contexts, that's probably the source of your confusion.

It can be used as a object reference which refers to the instance the current method was called on: return this;

It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:

MyClass(String name)
{
    this.name = name;
}

It can be used to invoke a different constructor of a a class from within a constructor:

MyClass()
{
    this("default name");
}

It can be used to access enclosing instances from within a nested class:

public class MyClass
{
    String name;

    public class MyClass
    {
        String name;

        public String getOuterName()
        {
            return MyClass.this.name;
        }
    }
}
Michael Borgwardt
+1  A: 

It's a reference of actual instance of a class inside a method of the same class. coding

public class A{
    int attr=10;

    public int calc(){
     return this.getA()+10;
   }
   /**
   *get and set
   **/    

}//end class A

In calc() body, the software runs a method inside the object allocated currently.

How it's possible that the behaviour of the object can see itself? With the this keyword, exactly.

Really, the this keyword not requires a obligatory use (as super) because the JVM knows where call a method in the memory area, but in my opinion this make the code more readeable.

alepuzio
+1  A: 

It can be also a way to access information on the current context. For example:

public class OuterClass
{
  public static void main(String[] args)
  {
    OuterClass oc = new OuterClass();
  }

  OuterClass()
  {
    InnerClass ic = new InnerClass(this);
  }

  class InnerClass
  {
    InnerClass(OuterClass oc)
    {
      System.out.println("Enclosing class: " + oc + " / " + oc.getClass());
      System.out.println("This class: " + this + " / " + this.getClass());
      System.out.println("Parent of this class: " + this.getClass().getEnclosingClass());
      System.out.println("Other way to parent: " + OuterClass.this);
    }
  }
}
PhiLho