Possible Duplicate:
When should I use “this” in a class?
How does one know whether to use "this" when referring to a field of an instance?
for example:
return this.name
i was taught one case where it is useful. i.e. when an input parameter is the same as the field's name:
public void setName(String name) {
    this.name = name;
}
Other than that, "this" seems unneeded.. What are some other cases?
When you have too many constructors for a class , you can use this to call other constructors. Example :
public class TeleScopePattern {
    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    public TeleScopePattern(int servingSize, int servings) {
        this(servingSize, servings, 0);
    }
    public TeleScopePattern(int servingSize, int servings, int calories) {
        this(servingSize, servings, calories, 0);
    }
    public TeleScopePattern(int servingSize, int servings, int calories, int fat) {
        this.servingSize = servingSize;
        this.servings = servings;
        this.calories = calories;
        this.fat = fat;
    }
}
                        You have to use this in a few cases:
when you have the same names of a field and a method parameter/local variable and you want to read/write the field
when you want to get access to a field of an outer class from an inner class:
class Outer {
    private String foo;
    class Inner {
        public void bar() {
             System.out.println(Outer.this.foo);
        }
    }
}
this(arg1, arg2); All other usages just a matter of style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With