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

时间:2013-04-05 03:48:35

标签: java scope this instance local

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

示例:

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

我希望他错了,但我找不到任何争论。

8 个答案:

答案 0 :(得分:37)

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

它可以在其他时间使用,但我们中的许多人认为它只是在代码中添加了不必要的措辞。

答案 1 :(得分:22)

如果需要,必须使用this,因为名称冲突,但最好完全避免这些。

如果您愿意,可以使用this。这纯粹是一种品味问题。

如果您的老师要求,

答案 2 :(得分:2)

this是实例中当前实例的别名或名称。它有助于消除本地变量(包括参数)的实例变量,但它本身可以用来简单地引用成员变量和方法,调用其他构造函数重载,或者只是引用实例。
请参阅{{ 3}}
这也是指当前的对象。如果你有类变量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.
}
}

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

        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

答案 3 :(得分:2)

如果您没有使用this关键字,那么您的老师是正确的,它将导致双重搜索编译器。首先,如果编译器无法在本地范围内找到变量,编译器将在本地范围内搜索,然后搜索实例范围。

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

答案 4 :(得分:1)

由于每个人都提供了消除歧义名称的示例,我将在使用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);
    }

}

答案 5 :(得分:0)

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

答案 6 :(得分:0)

我偶尔使用this因为自动完成(让生活变得更轻松),但我之后会将它们清理干净。

请记住,清晰度是关键。在这种情况下,很明显cont是一个类变量,但是如果你正在编写一个包含大量实例变量的庞大类,那么为了清晰起见,可以考虑使用this

当名称发生冲突时,您也需要才能使用this,例如

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

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

答案 7 :(得分:0)

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

public class Foo {

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

编译器不需要这个,但它使得查找foostring的情况更加清晰。除此之外(!),我只完全限定构造函数中的字段名称,它们可能被参数名称隐藏,正如许多其他海报在此处所示。

[编辑:现在我考虑一下,编译器需要这样做,例如Foohelper.toString()想要调用Foo.toString()。]