Search code examples
javacoding-styleconventionsinstance-variables

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;
    }   
}

Solution

  • 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.