java 当我想在方法中引用实例变量时,我应该使用“this”关键字吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15825590/
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-10-31 20:58:55  来源:igfitidea点击:

Should I use "this" keyword when I want to refer to instance variables within a method?

javascopethisinstancelocal

提问by Juan Herrera

My teacher says that when I try to access an instance variable within a method I should always use the thiskeyword, otherwise I would perform a double search. A local scope search and then an instance scope search.

我的老师说,当我尝试访问方法中的实例变量时,我应该始终使用this关键字,否则我会执行双重搜索。局部范围搜索,然后是实例范围搜索。

Example:

例子:

public class Test(){
    int cont=0;
    public void Method(){
        System.out.println(cont);//Should I use This.cont instead?
    }
}

I hope he is wrong, but I can't find any argument.

我希望他是错的,但我找不到任何论据。

回答by Hovercraft Full Of Eels

No, only use thiswhen you have a name conflict such as when a method parameter has the same name as an instance field that it is setting.

不,仅this当您有名称冲突时才使用,例如当方法参数与它正在设置的实例字段具有相同名称时。

It can be used at other times, but many of us feel that it simply adds unnecessary verbiage to the code.

它可以在其他时候使用,但我们中的许多人认为它只是在代码中增加了不必要的冗长。

回答by Andy Thomas

You mustuse thisif required because of a name conflict, though it's better to avoid those entirely.

由于名称冲突,您必须this在需要时使用,但最好完全避免使用它们。

You mayuse thisif you desire. It is purely a matter of taste.

可以使用this,如果你的愿望。这纯粹是一个品味问题。

You shoulduse thisin your schoolwork if your teacher demands it.

如果你的老师要求,你应该this在你的作业中使用它。

回答by Prasad

Your teacher is correct that it will result in double search for compiler if you don't make use of thiskeyword. First the compiler will search at local scope and then the instance scope if the compiler is unable to find the variable at local scope.

你的老师是对的,如果你不使用this关键字,它会导致对编译器的双重搜索。如果编译器无法在局部范围内找到变量,编译器将首先在本地范围内搜索,然后在实例范围内搜索。

Also, while the compiler is converting your code to bytecode, the compiler will prefix all the instance variables with thiskeyword. So, if you yourself make use of thiskeyword, you are actually reducing the burden to the compiler and the code will be compiled faster.

此外,当编译器将您的代码转换为字节码时,编译器将以this关键字作为所有实例变量的前缀。因此,如果您自己使用this关键字,实际上是在减轻编译器的负担,并且代码会编译得更快。

回答by Freak

thisis an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance.
See Java - when to use 'this' keyword
Also This refers current object. If you have class with variables int A and a method xyz part of the class has int A, just to differentiate which 'A' you are referring, you will use this.A. This is one example case only.

this是实例内当前实例的别名或名称。它对于从局部变量(包括参数)中消除实例变量的歧义很有用,但它本身可以用来简单地引用成员变量和方法,调用其他构造函数重载,或简单地引用实例。
请参阅Java - 何时使用“this”关键字
也这指的是当前对象。如果您的类具有变量 int A,并且类的方法 xyz 部分具有 int A,只是为了区分您指的是哪个“A”,您将使用 this.A。这只是一个示例案例。

public class Test
{
int a;

public void testMethod(int a)
{
this.a = a;
//Here this.a is variable 'a' of this instance. parameter 'a' is parameter.
}
}

So you may say that
this keyword can be used for (It cannot be used with static methods):

所以你可能会说
这个关键字可以用于(它不能与静态方法一起使用):

        1)To get reference of an object through which that method is 
        called within it(instance method).
        2)To avoid field shadowed by a method or constructor parameter.
        3)To invoke constructor of same class.
        4)In case of method overridden, this is used to invoke method of current class.
        5)To make reference to an inner class. e.g ClassName.this

回答by Genzer

Since everybody has given examples of disambiguating names, I will give an example when using thishelp:

既然大家都给出了消歧义的例子,那我就在使用this帮助的时候举个例子:

public class Person {
    private final firstName;
    private final lastName;
    private final Date birthdate;
    private final Address address;

    @Override
    public boolean equals(Object otherObject) {
        if (!(otherObject instanceof Person) {
            return false;
        }

        Person otherPerson = (Person) otherObject;

        // Using this here help distinguishing the current instance and the other.
        return this.firstName.equals(otherPerson.firstName)
            && this.lastName.equals(otherPerson.lastName)
            && this.birthdate.equals(otherPerson.birthDate)
            && this.address.equals(otherPerson.address);
    }

}

回答by Andrew Lazarus

Another place that thisis often used for readability is when an inner class object is referring to a field of its containing object.

另一个this经常用于提高可读性的地方是当内部类对象引用其包含对象的字段时。

public class Foo {

    String foostring;
    /* snip lots of code */
    private class Foohelper {
        void helperMethod(String bazstring) {
             Foo.this.foostring = bazstring;
             // etc.
        }
    }
}

The compiler doesn't need this, but it makes the situation where to look for foostringmore clear. Other than this (!), I only fully qualify field names in the constructor where they may be hidden by parameter names, as many other posters have illustrated here.

编译器不需要这个,但它使在哪里寻找的情况foostring更加清楚。除了这个(!),我只在构造函数中完全限定字段名称,它们可能被参数名称隐藏,正如许多其他海报在这里说明的那样。

[Edit: Now that I think about it, there are places the compiler needs this, e.g., if Foohelper.toString()wants to call Foo.toString().]

[编辑:现在我想起来了,编译器在某些地方需要这个,例如,如果Foohelper.toString()想调用Foo.toString().]

回答by Visionary Software Solutions

thisonly applies to the case where a parameter has the same name as a class property.

this仅适用于参数与类属性同名的情况。

public class Dog {
   String name;
   public Dog(String name) {
      name = name; //but which name? Are we just assigning a variable to itself?
      // here you could say this.name = name. Or you could rename one of the variables to resolve ambiguity
   }
}

回答by Visionary Software Solutions

I occasionally use thisbecause of autocompletion (makes life easier), but I clean them up afterwards.

this由于自动完成功能,我偶尔会使用(让生活更轻松),但之后我会清理它们。

Remember, clarity is key. In this case, it's obvious that contis a class variable, but if you were writing an enormous class with piles of instance variables, you might consider using thisfor clarity.

请记住,清晰是关键。在这种情况下,很明显它cont是一个类变量,但是如果您正在编写一个包含大量实例变量的巨大类,this为了清楚起见,您可能会考虑使用。

You also only needto use thiswhen there is a name collision, e.g.

你也只需要使用this的时候有一个名称冲突,例如,

public class Ex {
    int num;
    public Ex(int num) {
        this.num = num; 
    }
}

In this example, whereas num = num would cause a collision, "this" avoids it. This is the only time it is absolutely necessary, but again, often clarity is a higher priority.

在这个例子中,虽然 num = num 会导致冲突,但“this”避免了它。这是唯一绝对必要的时候,但同样,清晰度通常是更高的优先级。