Java 我什么时候应该在课堂上使用“this”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2411270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:15:10  来源:igfitidea点击:

When should I use "this" in a class?

javaoopthis

提问by Roman

I know that thisrefers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use xinstead of this.xin some of the methods? May be xwill refer to a variable which is local for the considered method? I mean variable which is seen only in this method.

我知道this那是指当前对象。但我不知道什么时候我真的需要使用它。例如,在某些方法中如果我使用x而不是有什么区别this.x吗?可能x会引用所考虑方法的局部变量?我的意思是仅在此方法中可见的变量。

What about this.method()? Can I use it? Should I use it. If I just use method(), will it not be, by default, applied to the current object?

怎么样this.method()?我可以使用它吗?我应该使用它。如果我只使用method(),默认情况下它不会应用于当前对象吗?

回答by William Brendel

The thiskeyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors from within a constructor.

this关键字主要用于三种情况。第一个也是最常见的是在 setter 方法中消除变量引用的歧义。第二种是需要将当前类实例作为参数传递给另一个对象的方法时。第三种是作为从构造函数内部调用备用构造函数的一种方式。

Case 1:Using thisto disambiguate variable references. In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set. We then assign the argument xto this.x. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".

案例1:使用this来消除歧义变量引用。在 Java setter 方法中,我们通常传入一个与我们试图设置的私有成员变量同名的参数。然后我们将参数分配xthis.x。这清楚地表明您将参数“name”的值分配给实例变量“name”。

public class Foo
{
    private String name;

    public void setName(String name) {
        this.name = name;
    }
}

Case 2:Using thisas an argument passed to another object.

案例2:使用this为传递到另一个对象的参数。

public class Foo
{
    public String useBarMethod() {
        Bar theBar = new Bar();
        return theBar.barMethod(this);
    }

    public String getName() {
        return "Foo";
    }
}

public class Bar
{
    public void barMethod(Foo obj) {
        obj.getName();
    }
}

Case 3:Using thisto call alternate constructors. In the comments, trinithiscorrectly pointed out another common use of this. When you have multiple constructors for a single class, you can use this(arg0, arg1, ...)to call another constructor of your choosing, provided you do so in the first line of your constructor.

案例3:使用this调用备用构造。在评论中,trinithis正确地指出了this. 当一个类有多个构造函数时,你可以使用this(arg0, arg1, ...)调用另一个你选择的构造函数,前提是你在构造函数的第一行这样做。

class Foo
{
    public Foo() {
        this("Some default value for bar");

        //optional other lines
    }

    public Foo(String bar) {
        // Do something with bar
    }
}

I have also seen thisused to emphasize the fact that an instance variable is being referenced (sans the need for disambiguation), but that is a rare case in my opinion.

我还看到this用于强调实例变量被引用的事实(不需要消歧),但在我看来这是一种罕见的情况。

回答by ChickenMilkBomb

Unless you have overlapping variable names, its really just for clarity when you're reading the code.

除非您有重叠的变量名称,否则它实际上只是为了在您阅读代码时清楚起见。

回答by Adam Robinson

The only needto use the this.qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between xand this.x.

唯一需要使用this.限定符的情况是当前范围内的另一个变量共享相同的名称,并且您想要引用实例成员(如威廉描述的那样)。除此之外,x和之间的行为没有区别this.x

回答by amit

Will be there any difference if I use "x" instead of "this.x" in some of the methods?

如果我在某些方法中使用“x”而不是“this.x”会有什么区别吗?

Usually not. But it makes a difference sometimes:

通常不会。但有时它会有所不同:

  class A {
     private int i;
     public A(int i) {
        this.i = i; // this.i can be used to disambiguate the i being referred to
     }
  }

If I just use "method()", will it not be, by default, applied to the current object?

如果我只使用“method()”,默认情况下它不会应用于当前对象吗?

Yes. But if needed, this.method()clarifies that the call is made by this object.

是的。但如果需要,this.method()说明调用是由这个对象进行的。

回答by froadie

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

您只需要使用this- 大多数人只使用它 - 当存在具有相同名称的重叠局部变量时。(例如,Setter 方法。)

Of course, another good reason to use thisis that it causes intellisense to pop up in IDEs :)

当然,另一个很好的使用理由this是它会导致智能感知在 IDE 中弹出:)

回答by doc

thisdoes not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. When you have to use it, depends on context. For example you have to use it, as you said, when you have local variable that shadows class variable and you want refer to class variable and not local one.

this不影响生成的代码 - 它是编译时操作符,无论有没有它生成的代码都是一样的。当你必须使用它时,取决于上下文。例如,您必须使用它,正如您所说,当您有局部变量影响类变量并且您想要引用类变量而不是局部变量时。

edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus

编辑:“结果代码将是相同的”我的意思当然是,当局部范围内的某些变量不隐藏属于类的变量时。因此

class POJO {
   protected int i;

   public void modify() {
      i = 9;
   }

   public void thisModify() {
      this.i = 9;
   }
}

resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name

两种方法的结果代码将相同。不同之处在于某些方法是否声明了同名的局部变量

  public void m() {
      int i;
      i = 9;  // i refers to variable in method's scope
      this.i = 9; // i refers to class variable
  }

回答by BlairHippo

Google turned up a page on the Sun site that discusses this a bit.

谷歌在 Sun 网站上打开了一个页面,对此进行了一些讨论。

You're right about the variable; thiscan indeed be used to differentiate a method variable from a class field.

你是对的变量;this确实可以用来区分方法变量和类字段。

    private int x;
    public void setX(int x) {
        this.x=x;
    }

However, I reallyhate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:

然而,我真的很讨厌那个约定。给两个不同的变量提供字面上相同的名称是产生错误的秘诀。我更喜欢以下方面的东西:

    private int x;
    public void setX(int newX) {
        x=newX;
    }

Same results, but with no chance of a bug where you accidentally refer to xwhen you really meant to be referring to xinstead.

相同的结果,但不会x出现您在真正打算引用时不小心引用的错误x

As to using it with a method, you're right about the effects; you'll get the same results with or without it. Can you use it? Sure. Should you use it? Up to you, but given that I personally think it's pointless verbosity that doesn't add any clarity (unless the code is crammed full of static import statements), I'm not inclined to use it myself.

至于将它与方法一起使用,您对效果的看法是正确的;不管有没有它,你都会得到相同的结果。你能用吗?当然。你应该使用它吗?由您决定,但考虑到我个人认为没有任何意义的冗长并没有增加任何清晰度(除非代码中塞满了静态导入语句),我不倾向于自己使用它。

回答by Christopher Oezbek

The second important use of this(beside hiding with a local variable as many answers already say) is when accessing an outer instance from a nested non-static class:

的第二个重要用途this(除了像许多答案一样使用局部变量隐藏)是从嵌套的非静态类访问外部实例时:

public class Outer {
  protected int a;

  public class Inner {
    protected int a;

    public int foo(){
      return Outer.this.a;
    }

    public Outer getOuter(){
      return Outer.this;
    }
  }
}

回答by giri

when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.

当有两个变量一个实例变量和另一个同名的局部变量时,我们使用它。引用当前正在执行的对象以避免名称之间的冲突。

回答by Benjamin

"this" is also useful when calling one constructor from another:

从另一个构造函数调用一个构造函数时,“this”也很有用:

public class MyClass {
    public MyClass(String foo) {
        this(foo, null);
    }
    public MyClass(String foo, String bar) {
        ...
    }
}