Java - when to use 'this' keyword [duplica

2019-01-01 15:11发布

This question already has an answer here:

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?

12条回答
听够珍惜
2楼-- · 2019-01-01 15:43

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.

查看更多
孤独总比滥情好
3楼-- · 2019-01-01 15:44

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;
    }
    ...
}
查看更多
牵手、夕阳
4楼-- · 2019-01-01 15:46

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.

查看更多
无色无味的生活
5楼-- · 2019-01-01 15:49

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.

查看更多
听够珍惜
6楼-- · 2019-01-01 15:49

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.

查看更多
心情的温度
7楼-- · 2019-01-01 15:54

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.
  }
}
查看更多
登录 后发表回答