tags:

views:

885

answers:

14

I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x instead of this.x in some of the methods? May be x will refer to a variable which is local for the considered method? I mean variable which is seen only in this method.

What about this.method()? Can I use it? Should I use it. If I just use method(), will it not be, by default, applied to the current object?

+34  A: 

The this keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors from within a constructor.

Example of Case 1: Using this to disambiguate variable references. In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set. We then assign the argument x to this.x.

public class Foo {

    private String name;

    // ...

    public void setName(String name) {
        // This makes it clear that you are assigning 
        // the value of the parameter "name" to the 
        // instance variable "name".
        this.name = name;
    }

    // ...
}

Example of Case 3: Using this to call alternate constructors. In the comments, trinithis correctly pointed out another common use of this. When you have multiple constructors for a single class, you can use this(arg0, arg1, ...) to call another constructor of your choosing, provided you do so in the first line of your constructor.

class Foo {

    public Foo() {
        this("Some default value for bar");

        // Additional code here will be executed 
        // after the other constructor is done.
    }

    public Foo(String bar) {
        // Do something with bar
    }

    // ...
}

I have also seen this used to emphasize the fact that an instance variable is being referenced (sans the need for disambiguation), but that is a rare case in my opinion.

William Brendel
+1 For mentioning that you can also pass _this_ as an argument. _this_ is not only used for scope disambiguation.
Alexandre Jasmin
Of course there is also `this(arg1, arg2, ...)` inside a constructor.
trinithis
Just wondering if adding others answers onto your own is common practice on SO? It seems to happen often enough.
Hazior
@Hazior: I tend to write a short answer and then add to it over time. Sometimes that overlaps with other people's answers, sometimes not. In the case of my latest edit, trinithis pointed out another common use of `this` that I forgot, so I added it to my answer. I don't see anything wrong with this because the end result is a better answer overall, which is precisely the purpose of SO. I also try to give credit wherever possible, as I did in the case of trinithis.
William Brendel
A: 

Unless you have overlapping variable names, its really just for clarity when you're reading the code.

NickAtuShip
Or clutter.....
Steve Kuo
+9  A: 

The only need to use the this. qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x and this.x.

Adam Robinson
And if you have duplicate names, one of your variables should be renamed as it's almost definitely named improperly. Or at the very least, could be named better.
Chad
@Chad: It's common practice in Java setter methods. However, outside of setter methods, your statements generally holds.
William Brendel
You may want to use `this.x` to make your code read a little bit more clearly also, the maintainability/readability of code is also a factor that you should be considering...
Redbeard 0x0A
@Chad: I cannot agree enthusiastically enough. Good Lord, just because "this." allows you to give two different variables the same name, why would you WANT to?
BlairHippo
@Blair: Reading your answer makes it clear that you don't prefer this practice in setter methods, but many people do (I'd include myself in that list). If I have a setter method that takes a value, clearly the value passed in is to be the "new" value, so adding "new" to the variable name seems to add needless redundancy to the public API.
Adam Robinson
I posted an answer that uses it in a little more unique format . . . I think. I refer to the whole object itself to add it to a list for later access.
Hazior
@Adam: I hear you. I know it's common practice, but I personally chalk this up to "If all the other developers are jumping off a cliff...." If your setter is doing anything interesting and not just a one-liner, I really do think you're asking for trouble if you give two different variables identical names. Just one code monkey's opinion, of course.
BlairHippo
@Blair: Make that two code monkeys.
Software Monkey
good answer. not need to long big answers. apart conventions (like setters) the only must place to use (this.) is when there are more than one variable with the same name in same scope.
erasmus
A: 

Will be there any difference if I use "x" instead of "this.x" in some of the methods?

Usually not. But it makes a difference sometimes:

  class A {
     private int i;
     public A(int i) {
        this.i = i; // this.i can be used to disambiguate the i being referred to
     }
  }

If I just use "method()", will it not be, by default, applied to the current object?

Yes. But if needed, this.method() clarifies that the call is made by this object.

Amit Kumar
A: 

You should use "this" when the variable in question is ambiguous. For example:

public void setX(int x){
  this.x = x; // this.x required because 'x' refers to the param
}
Justin Ethier
Talking about virtual methods with respect to a java question will just add confusion. Also, there's no need to be explicit: calling `this.method()` will never be different from calling `method()`: the most derived method will always be called. Adding `super.method()` into the mix just confuses that. http://www.smotricz.com/kabutz/Issue021.html
David Berger
A: 

Check out

http://msdn.microsoft.com/en-us/library/dk1507sz%28VS.80%29.aspx

Common uses are listed

Joe Pitz
While the article still presents correct information, the OP's question is about java, not C#.
Adam Robinson
what does this article have to do with Java?
fuzzy lollipop
http://java.sun.com/docs/books/tutorial/java/javaOO/thiskey.html
Joe Pitz
Oh I see, Even though the article presents correct information, but it is not from a java source, you are going to ding me, Maybe you need to go back a take a class in logic.
Joe Pitz
C# != Java that is the logic
fuzzy lollipop
C# and Java are pretty close, although Java doesn't support the indexer overloading... This page from MSDN might be more appropriate (J# reference) http://msdn.microsoft.com/en-us/library/ms177684(VS.80).aspx
Kevin McKelvin
@Joe Pitz - If this were a question purely about style, it would be unfair to ding you. We can mix information sources until the cows come home about what line to place braces on. But reading the question and several answers, it seems clear that there is at least some confusion about semantics. That being the case, it is better form to cite java sources. But you should be happy people are dinging you, as the ensuing vote war will probably raise your rep more than the answer alone would have.
David Berger
+9  A: 

You only need to use this - and most people only use it - when there's an overlapping local variable with the same name. (Setter methods, for example.)

Of course, another good reason to use this is that it causes intellisense to pop up in IDEs :)

froadie
+1 intellisense, yay for being lazy :)
Tanzelax
A: 

this does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. When you have to use it, depends on context. For example you have to use it, as you said, when you have local variable that shadows class variable and you want refer to class variable and not local one.

edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus

class POJO {
   protected int i;

   public void modify() {
      i = 9;
   }

   public void thisModify() {
      this.i = 9;
   }
}

resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name

  public void m() {
      int i;
      i = 9;  // i refers to variable in method's scope
      this.i = 9; // i refers to class variable
  }
doc
+2  A: 

Google turned up a page on the Sun site that discusses this a bit.

You're right about the variable; this can indeed be used to differentiate a method variable from a class field.

    private int x;
    public void setX(int x) {
        this.x=x;
    }

However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:

    private int x;
    public void setX(int newX) {
        x=newX;
    }

Same results, but with no chance of a bug where you accidentally refer to x when you really meant to be referring to x instead.

As to using it with a method, you're right about the effects; you'll get the same results with or without it. Can you use it? Sure. Should you use it? Up to you, but given that I personally think it's pointless verbosity that doesn't add any clarity (unless the code is crammed full of static import statements), I'm not inclined to use it myself.

BlairHippo
It's not a convention, it's a program language scoping mechanism. What you listed--using newX (I prefer pX for parameter x) is a convention.
Bill K
@Bill K: I don't understand the distinction you're making. I can choose to name the input variable x, or newX, or pX, or mangroveThroatWarblerX. How is choosing to give it a name identical to the variable it's setting NOT a convention, while prepending "new" or "p" or "Gratuitous Monty Python References" ARE conventions?
BlairHippo
"Gratuitoud Monty Python References" is not a convention, it's the LAW.
Adam Robinson
+1: We use a different naming standard for arguments and method variables than that for class variables for this reason. We abbreviate arguments/method vars and use full words for class/instance variables.
Software Monkey
Solving it by using a naming convention is, hmm, a convention. Solving it by using a language feature--I guess choosing to never use that language feature or always use it would be a convention... Using this. for every time you access a member would be a convention. Guess it doesn't matter much, I hate .this as well.
Bill K
+3  A: 

Personally I always use this as it always indicates that I am operating on an object's property or method. Especially in longer methods it helps to distinguish between declared variables and object properties.

This makes the code much cleaner and easier to understand imho and I don't have to care about shadowing of object properties.

Felix Kling
There are three schools ;) Some say it's better to do it in the BlairHippo's way. Some say it's better to use `this` all the time (like you). And others say that you should use it, when you have to. It's a matter of personal style. (In C++ you will find more poeople avoiding `this` because it is a bit harder to type "this->" than "this." in Java ;) )
doc
I've seen code like this--personally bugs the hell out of me--since it's human-based, it can be really misleading if wrong. If you actually TRUST that there is a this. in front of your properties (the only thing that makes your pattern worth while, why bother if you don't trust it???) then you are leaving yourself open for some human forgetting to type "this.". You should get in the habit of trusting your editor's colors. If you don't have colors set to differentiate variable types, change them. If you use an editor that doesn't have this capability, change it!
Bill K
__explicit__ is always better than implicit
fuzzy lollipop
I don't understand what is gained by putting this in front of a method. It doesn't convey any information as this and no-this work exactly the same for methods, overridden methods and static methods.
Steve Kuo
I understand that this is supposed to reduce the possibility of human error, but like Bill K said, it depends on the lack of human error.
Chris
`this` *does* convey information - it indicates that the member is an instance member (not static) and that it is a class-level member rather than a parameter.
Jeff Sternal
@Bill K: Well you also have to *trust* others that they don't shadow object properties with local variables and not using `this`. You have to trust them to use `this` properly. So it is the same both ways.
Felix Kling
@Jeff this in front of a static method is perfectly valid in Java. Thus when I see this.someMethod(), it could be a static, member, overridden method. In other words, it conveys no extra info. Also, Java does not support passing methods, so this does not disambiguate between methods and variables.
Steve Kuo
D'oh, thanks for setting me straight Steve - and it looks like it's too late for me to add 'depending on the language' D:.
Jeff Sternal
If explicit is always better than implicit, how about being clearer with a comment in front of the variable--that's essentially what it is, and it would be clearer if every time you accessed it you EXPLICITLY said "/* this is a member variable */, right? Or you could just let your GUI color it for you, always correct always explicit... Don't put duplicate (potentially conflicting) information in your code, right?
Bill K
Bill K
@Bill K: In the end it is a matter of taste. I like the fact that I know at a glance that a variable is a property or not without having to look for the declaration.
Felix Kling
@Felix No you don't know if something is not a member at a glance. You THINK it is, assuming you aren't editing my code, right (None of my code uses "this.", so you would glance at it and assume I don't use member variables? On the other hand, you could just look at the color--I ACTUALLY know at a glance, with no doubt, if a variable is a member or not. It's not actually a matter of taste--one is fallible, manual and (IMO) annoying, the other actually is reliable and simple--allowing the editor to automate fallible work for you.
Bill K
+9  A: 

The second important use of this (beside hiding with a local variable as many answers already say) is when accessing an outer instance from a nested non-static class:

public class Outer {
  protected int a;

  public class Inner {
    protected int a;

    public int foo(){
      return Outer.this.a;
    }

    public Outer getOuter(){
      return Outer.this;
    }
  }
}
Christopher Oezbek
A: 

when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.

giri
+5  A: 

"this" is also useful when calling one constructor from another:

public class MyClass {
    public MyClass(String foo) {
        this(foo, null);
    }
    public MyClass(String foo, String bar) {
        ...
    }
}
Benjamin
A: 

To make sure that the current object's members are used. Cases where thread safety is a concern, some applications may change the wrong objects member values, for that reason this should be applied to the member so that the correct object member value is used.

If your object is not concerned with thread safety then there is no reason to specify which object member's value is used.

Myster October
This really isn't the case. I'm not even sure what case you're thinking of, but an example might be helpful to understand what you're trying to say.
David Berger