Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
gotly
Oct 28, 2007
Economy-Sized
Sorry if this is really basic, it's been about 3-4 years since I've done any real Java and I don't know how to Google this because that's exactly what it's about : this.

When is it appropriate and when is it inappropriate to reference a variable/function/anything as this.exampleThing instead of just exampleThing? No need to re-invent the wheel, if someone could point me at the correct search term I'd really appreciate it. So far, I've just found "it's a style thing" which is kind of insane. Why put "this" in front of every god drat thing if it's not needed?


Edit:

stackoverflow posted:

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

Really? Really?

gotly fucked around with this message at 04:00 on Sep 3, 2011

Adbot
ADBOT LOVES YOU

gotly
Oct 28, 2007
Economy-Sized

carry on then posted:

Yeah, the only time I've ever seen it is when a parameter and an instance variable have the same name, or an instance variable and a local variable. (edit: I guess a parameter is just a local variable, isn't it?)

code:
public class MyClass {
    int number; //BUTTS

    public MyClass(int number) { //CHEWBACCA
        this.number = number;
    }
}
I'm sure with a bit of work you could always make sure the names are different. What's the consensus on which one is best?


Just to make sure I have it 100% - in this case, MyClass will actually change BUTTS and leave CHEWBACCA alone?

gotly
Oct 28, 2007
Economy-Sized
Thanks guys, cleared it up a lot. I program in something drastically different during the day so it's always nice to see what seasoned Java guys consider best practice. Also, if I could write production code like baquerd I'd die a happy man.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply