简体   繁体   English

设置实例变量与方法参数同名吗?

[英]Setting instance variable with same name as method parameter?

If I have code like this: 如果我有这样的代码:

public class Foo {
    public int bar;

    public void setBar(int bar) {
        bar = bar;
    }
}

Eclipse warns me that the assignment doesn't do anything (for obvious reasons). Eclipse警告我,该分配不会执行任何操作(出于明显的原因)。 Can I fix it by changing it to this.bar = bar; 我可以通过将其更改为this.bar = bar;来修复它吗this.bar = bar; or is it best to just use a different variable name? 还是最好只使用一个不同的变量名?

Using this.bar = bar; 使用this.bar = bar; is just fine. 很好 Most setters are coded this way. 大多数二传手都是这样编码的。

When you need to do something like that, one common course of action is to rename the function parameter. 当您需要执行类似操作时,一种常见的做法是重命名function参数。

public void setBar(int theBar) {
    bar = theBar;
}

If you would rather not do that, use this. 如果您不想这样做,请使用this. prefix, like this: 前缀,像这样:

this.bar = bar;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java实例变量和具有相同名称的方法 - java instance variable and method having same name 如何使实例变量的名称与构造函数参数的名称相同? - How to keep the name of the instance variable same as that of constructor parameter? 将实例变量作为参数传递给同一个类中的方法? - passing instance variable as parameter in method within same class? 静态方法和实例方法同名? - Static and instance method with same name? 实例变量可以由方法使用,局部变量也可以在方法内部以与Java中的实例变量相同的名称声明 - Instance Variable can be used by method and also local variable can be declared inside the method with the same name as of instance variable in Java 局部变量和实例变量同名 - Local variable and instance variable has the same name 如何在Java中区分私有实例变量和具有相同名称的参数 - How to differentiate between the private instance variable and a parameter having same name in java 即使之前初始化了一个同名的实例变量,当我在方法中再次初始化时会发生什么 - what happens when i initialize again in method even though previously initialized a instance variable with same name 在java中传递同名的局部变量和实例变量 - passing local and instance variable with same name in java Java - 静态变量和具有相同名称的参数 - Java - static variable and parameter with same name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM