方法的类和参数可以干扰吗? [英] Can fields of the class and arguments of the method interfere?

查看:64
本文介绍了方法的类和参数可以干扰吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有称为"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)?

推荐答案

本地作用域具有更高的优先级,因此参数a将隐藏字段a.实际上,您将参数a的值设置为其自身.避免名称冲突(并提高可读性)的正确习惯是使用this显式标记类成员:

The more local scope has the priority, so the parameter a will hide the field a. In effect, you set the value of parameter a to itself. The proper idiom to avoid name clashes (and improve readability) is to use this to explicitly mark the class member:

public void setA(String a) {
  this.a = a;
}

局部变量与成员变量相同:局部变量隐藏具有相同名称的成员变量.

The same is true for local variables vs member variables: local variables hide member variables with the same name.

这篇关于方法的类和参数可以干扰吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆