Java - when to use 'this' keyword [duplicate]

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?


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.

As reference, you can check the Oracle's Java Tutorials out about this.subject ;-)

http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html


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'!


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.