1

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?

1
  • 2
    this.foo = foo; is an accepted convention in a set method or constructor. Commented May 13, 2014 at 1:53

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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;

4 Comments

@azurefrog It is often a team decision, when the team decides on the common coding standards. I've seen it done both ways.
Thanks, this is for an assignment where we are given the method signatures so it's probably better for me to use this rather than changing it the parameter name.
@LionKing34 Parameter names are not part of a method signature, so you can freely change them.
@dasblinkenlight True, I meant we were given the Javadoc file which does have paremeter names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.