views:

673

answers:

11

What is the best practise for using the this keyword in Java? For example, I have the following class:

class Foo {
    Bar bar;

    public Foo(Bar bar) {
         this.bar = bar;
    }
}

That's fine and all, but Java is clever enough to know what is happening if I change the statement in the constructor to

 bar = bar;

So why use the this keyword? (I realise in some situations, it's totally necessary to use it, I'm just asking for situations like this). Actually, I tend to use the keyword purely for readability sake but what's the common practise? Using it all over the shop makes my code look a bit messy, for example

boolean baz;
int someIndex = 5;
this.baz = this.bar.getSomeNumber() == this.someBarArray[this.someIndex].getSomeNumber();

Obviously a poor bit of code but it illustrates my example. Is it just down to personal preference in these cases?

+2  A: 

It is a personal preference - choose a style and stick to it. I personally use this but others think it is redundant.

Andrew Hare
+13  A: 

but Java is clever enough to know what is happening if I change the statement in the constructor to

  bar = bar;

FALSE! It compiles but it doesn't do what you think it does!

As to when to use it, a lot of it is personal preference. I like to use this in my public methods, even when it's unnecessary, because that's where the interfacing happens and it's nice to assert what's mine and what's not.

polygenelubricants
Thats why I like to mark all parameter variables as final.
crowne
yeah it just reassigns the variable bar in the contructor to itself. This is because bar is already defined in the scope and it overides the one from Bar bar.
A: 

Depending on convention, you can use it for readability. It stresses the fact that it's an object variable.

I also like to have setter arguments with the same name as the variable (looks better in method signature). You need this in this case.

Konrad Garus
+2  A: 

Actually

baz = baz

will raise this warining

The assignment to variable baz has no effect

So what you think is wrong, the local scope overrides the class attribute so you MUST use this keyword explictly to assign the variable to the class attribute.

Otherwise the variable accounted into assignment is just the one passed as a parameter and the class one is ignored. That's why this is useful, it's not a fact of readability, it's a fact of explicitly deciding which baz are you talking about.

I would say

use this wherever not using it would cause ambiguities (or compiler warning, that are more important), otherwise just leave it. Since its purpose is exactly to solve ambiguities when default assumptions (first check locals, then check class attributes) are not enough.

Jack
+1  A: 

You should use it when you have a parameter with the same name as a field otherwise you will run into issues. It will compile, but won't necessarily do what you want it to.

As for everywhere else, don't use it unless it's needed for readability's sake. If you use it everywhere, 20% of your code will consist of the word 'this'!

Donal Boyle
+1  A: 

public Foo(Bar bar) { this.bar = bar; } is not the same as

public Foo(Bar bar) { bar = bar; }

In the second case the bar in scope is the parameter, so you assign it to itself. this.bar remains null.

David Soroko
+1  A: 

Personal preference, but I use it to solve ambiguities only, and I suppose in the very rare case to make it obvious that the assigned variable is a field. There are some projects where people use "this.field" on every single field reference. I find this practice visually distracting to the point of being obnoxious, but you should be prepared to see such code once in a while.

I secretly think there's a special place in hell for people who write 500 line classes that have 275 'this' keywords in them, but this style is found in some open source projects, so to each his own I guess.

JPDecker
+1 If find using this.* everywhere very annoying.If you're using a modern IDE, and design classes properly, you'll never run into a situation where you have to figure out what the refered to variable is (attribute, local variable etc.)
Helper Method
A: 

I always try to use this keyword on local class objects.

I use it to visually remind me if an object is static object or class object.

It helps me and the compiler differentiate between method args and local class object.

public void setValue(int value){
  this.value = value;
}

It helps me to visually remind me if there is such a local object in an inner/nested/anonymous class to differentiate it from encapsulating class objects. Because if there is not this prefixed, my convention will remind me that it is an object of the encapsulating class

public class Hello{
  public int value = 0;
  public boolean modal = false;

  public class Hellee{
    public int value = 1;
    public getValue(){
      if (modal)
        return 0;
      return this.value;
    }
  }
}
Blessed Geek
A: 

this keyword refers to the Object of class on which some method is invoked..

for example: public class Xyz {

public Xyz(Abc ob)
{
    ob.show();
}

}

public class Abc {

int a =10;
public Abc()
{
    new Xyz(this);
}
public void show()
{
    System.out.println("Value of a " + a);
}
public static void main(String s[])
{
    new Abc();
}

}

Here in Abc() we are calling Xyz() which needs Object of Abc Class.. So we can pass 'this' instead of new Abc(), because if we pass new Abc() here it will call itself again and again.

Also we use this to differentiate variables of class and local variables of method.

e.g

class Abc{ int a; void setValue(int a) { this.a = a; } }

here this.a is refers to variable a of class Abc. Hence having same effect as you use new Abc().a;

so you can say 'this' refers to object of current class.

A: 

Use it for Cloning objects (by passing reference of itself through a copy constructor).

Useful for object that inherits Cloneable.

public Foo implements Cloneable {
  private String bar;

  public Foo(Foo who) {
    bar = who.bar;
  }

  public Object getClone() {
    return new Foo(this);  //Return new copy of self.
  }
}
The Elite Gentleman
A: 

void set(int real) { this.real=real; } here this is a keyword used when there is instance variable is same as the local variable; another use of this constructor overloading it can call the constructor in a overloaded constructor

lagnajit