Java - when to use 'this' keyword

JavaCoding StyleThis

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

> 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

Solution 2 - Java

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

Solution 3 - Java

Actually

baz = baz

will raise this warning

> 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.

Solution 4 - Java

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.

Solution 5 - Java

It is common to use this keyword in explicit constructor invocation. You can see an example from the documentation.

public class Rectangle {
    private int x, y;
    private int width, height;
        
    public Rectangle() {
        this(0, 0, 1, 1);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}

Solution 6 - Java

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.

Solution 7 - Java

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

Solution 8 - Java

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.

Solution 9 - Java

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;
    }
  }
}

Solution 10 - Java

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 is constructor overloading. it can call the constructor in a overloaded constructor.

Solution 11 - Java

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.

Solution 12 - Java

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.
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjackbotView Question on Stackoverflow
Solution 1 - JavapolygenelubricantsView Answer on Stackoverflow
Solution 2 - JavaDónal BoyleView Answer on Stackoverflow
Solution 3 - JavaJackView Answer on Stackoverflow
Solution 4 - Javauser291977View Answer on Stackoverflow
Solution 5 - JavaDmitriy PanchyshynView Answer on Stackoverflow
Solution 6 - JavaDavid SorokoView Answer on Stackoverflow
Solution 7 - JavaAndrew HareView Answer on Stackoverflow
Solution 8 - JavaKonrad GarusView Answer on Stackoverflow
Solution 9 - JavaBlessed GeekView Answer on Stackoverflow
Solution 10 - JavalagnajitView Answer on Stackoverflow
Solution 11 - JavaDeckerView Answer on Stackoverflow
Solution 12 - JavaBuhake SindiView Answer on Stackoverflow