james
james

Reputation: 3573

Conventional usage of "this" in Java class to refer to an instance variable

Is the following usage of "this" to refer to an instance variable in the current class acceptable? In PHP this is how you would have to do it, but I noticed in Java you can just call the variable by name directly.

I personally find "this.variable" to be more understandable but I don't want to develop bad coding habits if that isn't normal.

Thanks!

public class MyClass {  

    /**
     * Private variable
     */
    private int myInt;

    /**
     * Setter method
     */
    public void setMyInt(int value) {
        this.myInt = value;
    }   
}

Upvotes: 3

Views: 500

Answers (5)

Khalos
Khalos

Reputation: 2373

Like people have been saying, its not required, but it is acceptable.

That being said it is necessary if you're doing something like this:

private int value;

public void setValue(int value) {
     this.value = value;
}

Which differentiates between the class variable and the parameter with the same name. I find myself using this pattern in almost every setter I make, and is about the only time I use the 'this' keyword.

Upvotes: 7

Mot
Mot

Reputation: 29530

I'd write your code like this:

public class MyClass {

  private int myInt;

  public void setMyInt(int myInt) {
    this.myInt = myInt;
  }
}

The difference to yours is (beside having removed useless Javadoc) that in my code the parameter has the same name as the member variable. Other users prefer to give the member variable a different name than the parameter, but we prefer to prefix the member variables where necessary with this. because of visual balance. In over 10 years of Java coding using this standard we never had a bug which was caused by using the wrong variable.

Upvotes: 1

bcat
bcat

Reputation: 8941

Unless your workplace or project has a style guide the specifically prohibits using this in this manner, I'd say what you're doing is perfectly fine. I personally use this only when it's strictly necessary (e.g., when I'm initializing an instance variable with a method parameter of the same name), but I've seen plenty of code that always uses this to reference members. It might be more readable, and it certainly isn't much less readable, so go for it!

Upvotes: 0

Reese Moore
Reese Moore

Reputation: 11640

Use it or don't, just be consistent throughout the codebase. You have to use it if the variable is masked though (by an argument or a local method variable)

Upvotes: 0

Madison Caldwell
Madison Caldwell

Reputation: 862

This is perfectly acceptable practice in Java, although it's not required (as you mentioned).

Upvotes: 1

Related Questions