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
Should I use "this" keyword when I want to refer to instance variables within a method?
提问by Juan Herrera
My teacher says that when I try to access an instance variable within a method I should always use the this
keyword, 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 this
when 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 this
if required because of a name conflict, though it's better to avoid those entirely.
由于名称冲突,您必须this
在需要时使用,但最好完全避免使用它们。
You mayuse this
if you desire. It is purely a matter of taste.
您可以使用this
,如果你的愿望。这纯粹是一个品味问题。
You shoulduse this
in 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 this
keyword. 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 this
keyword. So, if you yourself make use of this
keyword, you are actually reducing the burden to the compiler and the code will be compiled faster.
此外,当编译器将您的代码转换为字节码时,编译器将以this
关键字作为所有实例变量的前缀。因此,如果您自己使用this
关键字,实际上是在减轻编译器的负担,并且代码会编译得更快。
回答by Freak
this
is 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 this
help:
既然大家都给出了消歧义的例子,那我就在使用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 this
is 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 foostring
more 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
this
only 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 this
because of autocompletion (makes life easier), but I clean them up afterwards.
this
由于自动完成功能,我偶尔会使用(让生活更轻松),但之后我会清理它们。
Remember, clarity is key. In this case, it's obvious that cont
is a class variable, but if you were writing an enormous class with piles of instance variables, you might consider using this
for clarity.
请记住,清晰是关键。在这种情况下,很明显它cont
是一个类变量,但是如果您正在编写一个包含大量实例变量的巨大类,this
为了清楚起见,您可能会考虑使用。
You also only needto use this
when 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”避免了它。这是唯一绝对必要的时候,但同样,清晰度通常是更高的优先级。