Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it appropriate to use "this" in Java [duplicate]

Tags:

java

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?

like image 893
James Avatar asked Aug 16 '12 15:08

James


2 Answers

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;

    }

}
like image 110
invariant Avatar answered Oct 16 '22 01:10

invariant


You have to use this in a few cases:

  1. when you have the same names of a field and a method parameter/local variable and you want to read/write the field

  2. 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);
            }
        }
    }
    
  3. When you want to call one constructor from another one (but it's rather like a method call - this(arg1, arg2);

All other usages just a matter of style.

like image 5
Roman Avatar answered Oct 16 '22 02:10

Roman