wumbo
wumbo

Reputation: 746

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). Can I fix it by changing it to this.bar = bar; or is it best to just use a different variable name?

Upvotes: 1

Views: 173

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

When you need to do something like that, one common course of action is to rename the function parameter.

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

If you would rather not do that, use this. prefix, like this:

this.bar = bar;

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Using this.bar = bar; is just fine. Most setters are coded this way.

Upvotes: 3

Related Questions