类的字段和方法的参数会干扰吗?
我有一个带有名为“a”的字段的类。在类中我有一个方法,在该方法的参数列表中我也有“a”。那么,我会在方法内部看到哪个“a”?它是字段还是方法的参数?
public class myClass {
private String a;
// Method which sets the value of the field "a".
public void setA(String a) {
a = a;
}
}
顺便说一下,还有类似的情况。方法有一些局部(方法)变量,其名称与字段名称一致。如果我在方法内引用这样的方法局部变量(字段或局部变量),那么该方法会“看到”什么?
I have a class with a fields called "a". In the class I have a method and in the list of arguments of this method I also have "a". So, which "a" I will see inside of the method? Will it be the field or it will be the argument of the method?
public class myClass {
private String a;
// Method which sets the value of the field "a".
public void setA(String a) {
a = a;
}
}
By the way, there is a similar situation. A method has some local (for method) variables whose names coincide with the names of the fields. What will the "see" the method if I refer to such a method-local variable inside the method (the field or the local variable)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
更本地的范围具有优先权,因此参数
a
将隐藏字段a
。实际上,您将参数a
的值设置为其自身。避免名称冲突(并提高可读性)的正确习惯用法是使用this
显式标记类成员:局部变量与成员变量也是如此:局部变量隐藏同名的成员变量。
The more local scope has the priority, so the parameter
a
will hide the fielda
. In effect, you set the value of parametera
to itself. The proper idiom to avoid name clashes (and improve readability) is to usethis
to explicitly mark the class member:The same is true for local variables vs member variables: local variables hide member variables with the same name.
要添加到所有建议的答案中:
重要的是要认识到省略
this
只会将参数设置为其自身。通过使用final
,您可以消除由于省略
this
而导致的错误。当指定不需要更改的参数和字段时,使用final
是一个很好的做法。To add to all the answers recommending:
it's important to realise that omitting the
this
will simply set the parameter to itself. By usingfinal
thusyou can eliminate errors caused by omitting
this
. Usingfinal
is a good practise whenever specifying parameters and fields that aren't intentionally required to change.最接近的一个。也就是说,
在方法内部没有任何作用,因为两者都引用参数 a。要引用实例变量 a,可以使用 this 关键字。
The closest one. That is,
inside the method has no effect since both refer to the argument a. To refer to the instance variable a you use the this keyword.
本地版本将使用相同的名称“隐藏”实例变量。在像您这样的访问器中解决此问题的一种模式是:
它使用
this
关键字来明确范围。The local version will "shadow" the instance variable by the same name. One pattern to get around this in accessors like your is this:
which uses the
this
keyword to be explicit about scope.您需要使用
this
来访问class
变量,否则它将始终采用参数变量。You need to use
this
to access theclass
variable, otherwise it will always take the parameter variable.