简体   繁体   English

我什么时候应该在 class 中使用“this”?

[英]When should I use "this" in a class?

I know that this refers to a current object.我知道this是指当前的 object。 But I do not know when I really need to use it.但我不知道什么时候我真的需要使用它。 For example, will be there any difference if I use x instead of this.x in some of the methods?例如,如果我在某些方法中使用x而不是this.x会有什么不同吗? May be x will refer to a variable which is local for the considered method?可能x将引用所考虑方法的本地变量? I mean variable which is seen only in this method.我的意思是仅在此方法中可见的变量。

What about this.method() ? 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?如果我只使用method() ,默认情况下它不会应用于当前的 object 吗?

The this keyword is primarily used in three situations. this关键字主要用于三种情况。 The first and most common is in setter methods to disambiguate variable references.第一个也是最常见的是在 setter 方法中消除变量引用的歧义。 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.第三种是作为从构造函数中调用备用构造函数的一种方式。

Case 1: Using this to disambiguate variable references.案例 1:使用this来消除变量引用的歧义。 In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set.在 Java setter 方法中,我们通常传入一个与我们试图设置的私有成员变量同名的参数。 We then assign the argument x to this.x .然后我们将参数x分配给this.x This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".这清楚地表明您正在将参数“name”的值分配给实例变量“name”。

public class Foo
{
    private String name;

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

Case 2: Using this as 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 this to call alternate constructors.案例 3:使用this调用备用构造函数。 In the comments, trinithis correctly pointed out another common use of this .在评论中, trinithis正确地指出了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.当一个类有多个构造函数时,您可以使用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 this used 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用于强调实例变量被引用的事实(不需要消除歧义),但在我看来这是一种罕见的情况。

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

You only need to use this<\/code> - and most people only use it - when there's an overlapping local variable with the same name.你只需要使用this<\/code> ——而且大多数人只使用它——当有一个同名的局部变量重叠时。 (Setter methods, for example.) (例如,Setter 方法。)

Of course, another good reason to use this<\/code> is that it causes intellisense to pop up in IDEs :)当然,使用this<\/code>的另一个好理由是它会导致智能感知在 IDE 中弹出 :)

"

The only need to use the this.唯一需要用到的就是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).限定符是当当前范围内的另一个变量共享相同的名称并且您想要引用实例成员时(如 William 所描述的)。 Apart from that, there's no difference in behavior between x and this.x .除此之外, xthis.x之间的行为没有区别。

"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) {
        ...
    }
}

There are a lot of good answers, but there is another very minor reason to put this<\/code> everywhere.有很多很好的答案,但是还有另一个非常小的理由把this<\/code>放在任何地方。 If you have tried opening your source codes from a normal text editor (eg notepad etc), using this<\/code> will make it a whole lot clearer to read.如果您尝试从普通的文本编辑器(例如记事本等)打开源代码,使用this<\/code>会使阅读更加清晰。

Imagine this:想象一下:

public class Hello {
    private String foo;

    // Some 10k lines of codes

    private String getStringFromSomewhere() {
        // ....
    }

    // More codes

    public class World {
        private String bar;

        // Another 10k lines of codes

        public void doSomething() {
            // More codes
            foo = "FOO";
            // More codes
            String s = getStringFromSomewhere();
            // More codes
            bar = s;
        }
    }
}

this<\/code> is useful in the builder pattern. this<\/code>在构建器模式中很有用。

public class User {

    private String firstName;
    private String surname;

    public User(Builder builder){
        firstName = builder.firstName;
        surname = builder.surname;
    }

    public String getFirstName(){
        return firstName;
    }

    public String getSurname(){
        return surname;
    }

    public static class Builder {
        private String firstName;
        private String surname;

        public Builder setFirstName(String firstName) {
            this.firstName = firstName;
            return this;
        }

        public Builder setSurname(String surname) {
            this.surname = surname;
            return this;
        }

        public User build(){
            return new User(this);
        }

    }

    public static void main(String[] args) {
        User.Builder builder = new User.Builder();
        User user = builder.setFirstName("John").setSurname("Doe").build();
    }

}

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

"

@William Brendel answer provided three different use cases in nice way. @William Brendel 的回答以很好的方式提供了三种不同的用例。

Use case 1:<\/em><\/strong>用例 1:<\/em><\/strong>

Offical java documentation page on this<\/a> provides same use-cases.官方 java 文档页面提供了<\/a>相同的用例。

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called.在实例方法或构造函数中,this 是对当前对象的引用——调用其方法或构造函数的对象。 You can refer to any member of the current object from within an instance method or a constructor by using this.您可以使用 this 从实例方法或构造函数中引用当前对象的任何成员。

<\/blockquote>

It covers two examples :它涵盖了两个示例:

Using this with a Field<\/em> and Using this with a Constructor<\/em>将 this 与字段一起<\/em>使用并将其与构造函数一起使用<\/em>

Use case 2:<\/em><\/strong>用例 2:<\/em><\/strong>

Other use case which has not been quoted in this post: this<\/code> can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.本文未引用的其他用例: this<\/code>可用于同步多线程应用程序中的当前对象,以保护数据和方法的关键部分。

 synchronized(this){ \/\/ Do some thing. }<\/code><\/pre>

Use case 3:<\/em><\/strong>用例 3:<\/em><\/strong>

Implementation of Builder<\/a> pattern depends on use of this<\/code> to return the modified object. Builder<\/a>模式的实现依赖于使用this<\/code>来返回修改后的对象。

Refer to this post参考这篇文章

Keeping builder in separate class (fluent interface)<\/a> 将构建器保持在单独的类中(流畅的界面)<\/a>

"

Google turned up a page on the Sun site that discusses this a bit. 谷歌在 Sun 网站上打开了一个页面,讨论了这一点。

You're right about the variable;您对变量是正确的; this can 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 really hate 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 x when you really meant to be referring to x instead.结果相同,但不会出现错误,即当您真正打算引用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.由你决定,但鉴于我个人认为这是毫无意义的冗长,不会增加任何清晰度(除非代码塞满了静态导入语句),我不倾向于自己使用它。

Following are the ways to use 'this' keyword in java :以下是在 java 中使用 'this' 关键字的方法:

  1. Using this keyword to refer current class instance variables使用this关键字来引用当前类实例变量
  2. Using this() to invoke current class constructor使用this()调用当前类的构造函数
  3. Using this keyword to return the current class instance使用this关键字返回当前的类实例
  4. Using this keyword as method parameter使用this关键字作为方法参数

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

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.引用当前执行对象以避免名称之间的冲突。

this is a reference to the current object. this是对当前对象的引用。 It is used in the constructor to distinguish between the local and the current class variable which have the same name.它在构造函数中用于区分同名的本地和当前类变量。 eg:例如:

public class circle {
    int x;
    circle(int x){
        this.x =x;
        //class variable =local variable 
    }
} 

this can also be use to call one constructor from another constructor. this也可以用于从另一个构造函数调用一个构造函数。 eg:例如:

public class circle {
    int x;

    circle() { 
        this(1);
    }

    circle(int x) {
        this.x = x; 
    }
}

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

this<\/code> does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. this<\/code>不会影响生成的代码 - 它是编译时运算符,使用或不使用它生成的代码将是相同的。 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.例如,正如您所说,当您有隐藏类变量的局部变量并且您想要引用类变量而不是本地变量时,您必须使用它。

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

With respect to William Brendel<\/a> 's posts and dbconfessions<\/a> question, regarding case 2<\/strong> .关于William Brendel<\/a>的帖子和dbconfessions<\/a>问题,关于case 2<\/strong> 。 Here is an example:这是一个例子:

public class Window {

  private Window parent;

  public Window (Window parent) {
    this.parent = parent;
  }

  public void addSubWindow() {
    Window child = new Window(this);
    list.add(child);
  }

  public void printInfo() {
    if (parent == null) {
      System.out.println("root");
    } else {
      System.out.println("child");
    }
  }

}

“This” keyword in java is used to refer current class objects.<\/strong> java中的“this”关键字用于引用当前类对象。<\/strong>

There are 6 uses of “this” keyword in java java中“this”关键字的6种用法

  1. Accessing class level variable<\/strong> : mostly used if local and class level variable is same访问类级别变量<\/strong>:如果本地和类级别变量相同,则主要使用<\/li>
  2. Accessing class methods<\/strong> : this is default behavior and can be ignored访问类方法<\/strong>:这是默认行为,可以忽略<\/li>
  3. For calling other constructor<\/strong> of same class用于调用同一类的其他构造函数<\/strong><\/li>
  4. Using 'this' keyword as return value<\/strong> : for returning current instance from method使用 'this' 关键字作为返回值<\/strong>:用于从方法返回当前实例<\/li>
  5. Passing 'this' keyword as argument to method<\/strong> Passing : for passing current class instance as argument将“this”关键字作为参数传递给方法<\/strong>传递:用于将当前类实例作为参数传递<\/li>
  6. this keyword as argument to constructor<\/strong> : for passing current class instance as argument this 关键字作为构造函数的参数<\/strong>:用于将当前类实例作为参数传递<\/li><\/ol>

    ref: https:\/\/stacktraceguru.com\/java\/this-keyword-in-java<\/a>参考: https<\/a> :\/\/stacktraceguru.com\/java\/this-keyword-in-java

    "

To make sure that the current object's members are used.确保使用当前对象的成员。 Cases where thread safety is a concern, some applications may change the wrong objects member values, for that reason this should be applied to the member so that the correct object member value is used.在关注线程安全的情况下,某些应用程序可能会更改错误的对象成员值,因此应该将其应用于成员,以便使用正确的对象成员值。

If your object is not concerned with thread safety then there is no reason to specify which object member's value is used.如果您的对象不关心线程安全,则没有理由指定使用哪个对象成员的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM