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

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

例:

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

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

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

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

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

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

如果你的老师要求,你应该在你的功课中使用它。

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

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

  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. eg ClassName.this 

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

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

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

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

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

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

你也只需要在名称冲突时使用this ,例如

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

在这个例子中,虽然num = num会导致冲突,“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() 。]