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

时间:2022-09-10 23:44:17

I know that this refers 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 x instead of this.x in some of the methods? May be x will refer to a variable which is local for the considered method? I mean variable which is seen only in this method.

我知道这指的是当前对象。但是我不知道什么时候我真的需要使用它。例如,如果我用x代替这个会有什么不同。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(),那么它在默认情况下不会应用于当前对象吗?

17 个解决方案

#1


264  

The this keyword 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.

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

Case 1: Using this to 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 x to this.x. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".

案例1:使用它来消除变量引用的歧义。在Java setter方法中,我们通常传入一个与要设置的私有成员变量同名的参数。这表明您正在将参数“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:使用这个作为传递给另一个对象的参数。

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. In the comments, trinithis correctly 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:使用它调用备用构造函数。在评论中,trinithis正确地指出了另一个常见的用法。当您为一个类拥有多个构造函数时,您可以使用这个(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.

我也见过这种情况,它用来强调正在引用实例变量(不需要消除歧义),但在我看来,这种情况很少见。

#2


58  

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:

它的第二个重要用途(除了用局部变量隐藏之外,正如许多答案已经说过的)是从嵌套的非静态类访问外部实例时:

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

#3


37  

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

当有重叠的同名局部变量时,您只需要使用这个(大多数人也只使用它)。(Setter方法,例如)。

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

当然,使用它的另一个好理由是,它使智能感知在IDEs:

#4


19  

The only need to 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 x and this.x.

只需要用这个。qualifier是当当前作用域中的另一个变量共享相同的名称并且您希望引用实例成员时(如William所描述的)。除此之外,x和这个。x之间没有区别。

#5


15  

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

#6


9  

this is useful in the builder pattern.

这在构建器模式中很有用。

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

}

#7


5  

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

除非你有重叠的变量名,否则它只是为了在你阅读代码时更加清晰。

#8


3  

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.

你说得对;这确实可以用来区分方法变量和类字段。


    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.

说到用一种方法来使用它,你说得对;你会得到同样的结果。你能使用它吗?确定。你应该使用它吗?由您决定,但鉴于我个人认为这是毫无意义的冗长,不能增加任何清晰度(除非代码中满是静态导入语句),我不打算自己使用它。

#9


3  

@William Brendel answer provided three different use cases in nice way.

@William Brendel answer以很好的方式提供了三种不同的用例。

Use case 1:

用例1:

Offical java documentation page on this provides same use-cases.

关于这个的官方java文档页面提供了相同的用例。

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

在实例方法或构造函数中,这是对当前对象的引用——对象的方法或构造函数正在被调用。您可以通过使用实例方法或构造函数引用当前对象的任何成员。

It covers two examples :

它包括两个例子:

Using this with a Field and Using this with a Constructor

在字段中使用它,在构造函数中使用它

Use case 2:

用例2:

Other use case which has not been quoted in this post: this can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.

在本文中没有引用的其他用例:可以用来在多线程应用程序中同步当前对象,以保护数据和方法的关键部分。

synchronized(this){
    // Do some thing. 
}

Use case 3:

用例3:

Implementation of Builder pattern depends on use of this to return the modified object.

构建器模式的实现依赖于使用它来返回修改后的对象。

Refer to this post

参考这篇文章

Keeping builder in separate class (fluent interface)

将构建器保存在单独的类中(fluent接口)

#10


1  

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.

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

#11


1  

this is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:

这是对当前对象的引用。在构造函数中,它用于区分具有相同名称的本地变量和当前类变量。例如:

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. e.g.:

这也可以用于从另一个构造函数调用一个构造函数。例如:

public class circle {
    int x;

    circle() { 
        this(1);
    }

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

#12


1  

Following are the ways to use ‘this’ keyword in java :

以下是在java中使用“this”关键字的方法:

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

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

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

#13


1  

There are a lot of good answers, but there is another very minor reason to put this everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this will make it a whole lot clearer to read.

有很多很好的答案,但是还有一个很小的原因可以让它无处不在。如果你尝试过从普通的文本编辑器(如记事本等)打开你的源代码,使用它会使阅读更加清晰。

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 is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.

对于任何现代IDE来说,这都是显而易见的,但是对于普通的文本编辑器来说,这将是一场噩梦。

You will struggle to find out where foo resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere() for the same reason. Lastly, after you have forgotten what s is, that bar = s is going to give you the final blow.

在使用编辑器的“查找”函数之前,您将很难找到foo所在的位置。然后,出于同样的原因,您将向getStringFromSomewhere()尖叫。最后,在你忘了s是什么之后,那个bar = s会给你最后的打击。

Compare it to this:

比较:

public void doSomething() {
    // More codes
    Hello.this.foo = "FOO";
    // More codes
    String s = Hello.this.getStringFromSomewhere();
    // More codes
    this.bar = s;
}
  1. You know foo is a variable declared in outer class Hello.
  2. foo是在外层类Hello中声明的变量。
  3. You know getStringFromSomewhere() is a method declared in outer class as well.
  4. getStringFromSomewhere()也是在外部类中声明的方法。
  5. You know that bar belongs to World class, and s is a local variable declared in that method.
  6. 你知道bar属于World类,s是在那个方法中声明的一个局部变量。

Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.

当然,无论什么时候你设计什么东西,你都会创造规则。因此,在设计API或项目时,如果你的规则包括“如果有人用记事本打开所有这些源代码,他/她应该朝他/她的脑袋开枪”,那么你完全可以不这么做。

#14


0  

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

如果我用“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?

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

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

是的。但是如果需要,this.method()澄清调用是由这个对象发出的。

#15


0  

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

这不会影响生成的代码——它是编译时操作符,使用或不使用它生成的代码将是相同的。当你必须使用它时,这取决于上下文。例如,你必须使用它,就像你说的,当你有一个局部变量阴影类变量你想要引用类变量而不是局部变量。

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
  }

#16


0  

With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:

关于威廉·布伦德尔的文章,关于案例2的问题。这是一个例子:

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

}

I've seen this used, when building parent-child relation's with objects. However, please note that it is simplified for the sake of brevity.

我在构建父-子关系时见过这种用法。不过,请注意,为了简洁起见,它是简化的。

#17


-7  

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.

如果您的对象与线程安全性无关,则没有理由指定使用哪个对象成员的值。

#1


264  

The this keyword 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.

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

Case 1: Using this to 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 x to this.x. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".

案例1:使用它来消除变量引用的歧义。在Java setter方法中,我们通常传入一个与要设置的私有成员变量同名的参数。这表明您正在将参数“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:使用这个作为传递给另一个对象的参数。

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. In the comments, trinithis correctly 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:使用它调用备用构造函数。在评论中,trinithis正确地指出了另一个常见的用法。当您为一个类拥有多个构造函数时,您可以使用这个(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.

我也见过这种情况,它用来强调正在引用实例变量(不需要消除歧义),但在我看来,这种情况很少见。

#2


58  

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:

它的第二个重要用途(除了用局部变量隐藏之外,正如许多答案已经说过的)是从嵌套的非静态类访问外部实例时:

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

#3


37  

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

当有重叠的同名局部变量时,您只需要使用这个(大多数人也只使用它)。(Setter方法,例如)。

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

当然,使用它的另一个好理由是,它使智能感知在IDEs:

#4


19  

The only need to 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 x and this.x.

只需要用这个。qualifier是当当前作用域中的另一个变量共享相同的名称并且您希望引用实例成员时(如William所描述的)。除此之外,x和这个。x之间没有区别。

#5


15  

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

#6


9  

this is useful in the builder pattern.

这在构建器模式中很有用。

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

}

#7


5  

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

除非你有重叠的变量名,否则它只是为了在你阅读代码时更加清晰。

#8


3  

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.

你说得对;这确实可以用来区分方法变量和类字段。


    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.

说到用一种方法来使用它,你说得对;你会得到同样的结果。你能使用它吗?确定。你应该使用它吗?由您决定,但鉴于我个人认为这是毫无意义的冗长,不能增加任何清晰度(除非代码中满是静态导入语句),我不打算自己使用它。

#9


3  

@William Brendel answer provided three different use cases in nice way.

@William Brendel answer以很好的方式提供了三种不同的用例。

Use case 1:

用例1:

Offical java documentation page on this provides same use-cases.

关于这个的官方java文档页面提供了相同的用例。

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

在实例方法或构造函数中,这是对当前对象的引用——对象的方法或构造函数正在被调用。您可以通过使用实例方法或构造函数引用当前对象的任何成员。

It covers two examples :

它包括两个例子:

Using this with a Field and Using this with a Constructor

在字段中使用它,在构造函数中使用它

Use case 2:

用例2:

Other use case which has not been quoted in this post: this can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.

在本文中没有引用的其他用例:可以用来在多线程应用程序中同步当前对象,以保护数据和方法的关键部分。

synchronized(this){
    // Do some thing. 
}

Use case 3:

用例3:

Implementation of Builder pattern depends on use of this to return the modified object.

构建器模式的实现依赖于使用它来返回修改后的对象。

Refer to this post

参考这篇文章

Keeping builder in separate class (fluent interface)

将构建器保存在单独的类中(fluent接口)

#10


1  

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.

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

#11


1  

this is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:

这是对当前对象的引用。在构造函数中,它用于区分具有相同名称的本地变量和当前类变量。例如:

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. e.g.:

这也可以用于从另一个构造函数调用一个构造函数。例如:

public class circle {
    int x;

    circle() { 
        this(1);
    }

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

#12


1  

Following are the ways to use ‘this’ keyword in java :

以下是在java中使用“this”关键字的方法:

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

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

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

#13


1  

There are a lot of good answers, but there is another very minor reason to put this everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this will make it a whole lot clearer to read.

有很多很好的答案,但是还有一个很小的原因可以让它无处不在。如果你尝试过从普通的文本编辑器(如记事本等)打开你的源代码,使用它会使阅读更加清晰。

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 is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.

对于任何现代IDE来说,这都是显而易见的,但是对于普通的文本编辑器来说,这将是一场噩梦。

You will struggle to find out where foo resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere() for the same reason. Lastly, after you have forgotten what s is, that bar = s is going to give you the final blow.

在使用编辑器的“查找”函数之前,您将很难找到foo所在的位置。然后,出于同样的原因,您将向getStringFromSomewhere()尖叫。最后,在你忘了s是什么之后,那个bar = s会给你最后的打击。

Compare it to this:

比较:

public void doSomething() {
    // More codes
    Hello.this.foo = "FOO";
    // More codes
    String s = Hello.this.getStringFromSomewhere();
    // More codes
    this.bar = s;
}
  1. You know foo is a variable declared in outer class Hello.
  2. foo是在外层类Hello中声明的变量。
  3. You know getStringFromSomewhere() is a method declared in outer class as well.
  4. getStringFromSomewhere()也是在外部类中声明的方法。
  5. You know that bar belongs to World class, and s is a local variable declared in that method.
  6. 你知道bar属于World类,s是在那个方法中声明的一个局部变量。

Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.

当然,无论什么时候你设计什么东西,你都会创造规则。因此,在设计API或项目时,如果你的规则包括“如果有人用记事本打开所有这些源代码,他/她应该朝他/她的脑袋开枪”,那么你完全可以不这么做。

#14


0  

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

如果我用“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?

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

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

是的。但是如果需要,this.method()澄清调用是由这个对象发出的。

#15


0  

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

这不会影响生成的代码——它是编译时操作符,使用或不使用它生成的代码将是相同的。当你必须使用它时,这取决于上下文。例如,你必须使用它,就像你说的,当你有一个局部变量阴影类变量你想要引用类变量而不是局部变量。

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
  }

#16


0  

With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:

关于威廉·布伦德尔的文章,关于案例2的问题。这是一个例子:

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

}

I've seen this used, when building parent-child relation's with objects. However, please note that it is simplified for the sake of brevity.

我在构建父-子关系时见过这种用法。不过,请注意,为了简洁起见,它是简化的。

#17


-7  

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.

如果您的对象与线程安全性无关,则没有理由指定使用哪个对象成员的值。