12

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?

Community
  • 1
  • 1
James
  • 706
  • 3
  • 8
  • 16
  • 1
    No need to say it's easy - it's a good question – dfb Aug 16 '12 at 15:10
  • 5
    ...that's been asked before: http://stackoverflow.com/questions/2411270/when-should-i-use-this-in-a-class – martijno Aug 16 '12 at 15:12
  • Within an instance method or a constructor, `this` is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using `this`. –  Aug 16 '12 at 15:13

7 Answers7

6

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;

    }

}
invariant
  • 8,758
  • 9
  • 47
  • 61
  • You might also use this when calling a method outside of the class wanting to give a reference to yourself. ToStringUtil.toString(this); – JustinKSU Aug 16 '12 at 15:18
  • so "this(...);" is equivalent to calling TeleScopePattern(...)? – James Aug 16 '12 at 15:25
  • @James you mean for something like functor objects?... – Qnan Aug 16 '12 at 15:30
  • @Qnan sorry, I have no idea what functor objects are. But it's just strange how versatile "this" is if it can be both a function call as well as a parameter. Or is it just that flexible? – James Aug 16 '12 at 15:33
  • @James by "functor" I meant an object in C++ that mimics function behavior by overloading the `()` operator. I don't think these are present in Java. – Qnan Aug 16 '12 at 15:41
  • @Qnan so you are saying that this answer is not valid? – James Aug 16 '12 at 15:45
  • @James, let me rephrase it, my previous statement wasn't correct. The point is that `TeleScopePattern(...)` and `this(...)` are not equivalent. They do exactly the same thing (invoke to constructor), but appear in different contexts. – Qnan Aug 16 '12 at 15:50
5

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.

Roman
  • 64,384
  • 92
  • 238
  • 332
2

Aside from that case (which is quite common, tough I prefer to name the variable and the parameter differently so I can distinguish them better) and from using it as a constructor, there is another case.

Somethimes you want to pass the very instantiated object to a method. In that case you use this as a parameter for a method that recieves a class of that instance. For example, having a method with an auxiliar class that does increments:

public class MyClass {

    private Integer value = 0; //Assume this has setters and getters

    public void incrementValue() {
        Incrementer.addOne(this);
    }

}

And the incrementer class has a method like this one:

public static void addOne(MyClass classToIncrement) {
    Integer currentValue = classToIncrement.getValue();
    currentValue++;
    classToIncrement.setValue(currentValue);
}

For more information, check the documentation.

Fritz
  • 9,987
  • 4
  • 30
  • 49
  • 1
    Eeek, that's horrible engineering. The whole point of classes is that the data and operation upon the data are in the same place. – OrangeDog Aug 16 '12 at 15:21
  • Not to mention pointless use of boxed primitives. – OrangeDog Aug 16 '12 at 15:22
  • @OrangeDog It was just an example. What if you want to share common logic amongst classes that are not in the same object hierarchies? Since Java doesn't have multiple class inheritance you could center the logic in a helper class and use it. I'd use other Patterns in fact, this was just an example. About the pointless use of boxed primitives... please define pointless. You can't judge a man's craft based on a quick example that wants to point at a single fact. – Fritz Aug 16 '12 at 15:28
  • @OrangeDog so you are saying if addOne was in the same class as incrementValue, it would be better practice? Also, what is a boxed primitive.. – James Aug 16 '12 at 15:29
  • 1
    @James boxed primitive is `Integer`, while `int` is a regular primitive. The difference is that the former is an object, which has space allocated for it and a memory address of its own. – Qnan Aug 16 '12 at 15:31
  • 1
    @Gamb There is no reason whatsoever in the context of your example not to use `int`. Boxed primitives should only be used where necessary, as they come with both syntactic and performance costs. – OrangeDog Aug 16 '12 at 15:34
  • @James I'm saying it should be this: `public void incrementValue() { this.value++; }`, following the basic principles of Object-Oriented programming. – OrangeDog Aug 16 '12 at 15:35
  • aside from the issue of whether to use the boxed primitive or not, I see what @Gamb is trying to do. The entire instance of MyClass (whatever 'this' refers to) is passed into addOne where a field of 'this' is extracted and assigned to currentValue. am i right? – James Aug 16 '12 at 15:40
  • @James correct. Also, this is technically possible, but usually unnecessary. – Qnan Aug 16 '12 at 15:44
  • Indeed, I just covered a quite restricted and particular context with a simple example. I should have added more casts, classes and variables to state my point, not just a simple increment since it confused some readers. – Fritz Aug 16 '12 at 16:03
  • @Gamb regardless of the complexity of the system and the need for handler classes, they should be called as `Handler.doThing(object)`, not `object.pretendToDoThingYourself()`. – OrangeDog Aug 16 '12 at 16:27
2

The Fluent Interface pattern essentially means returning this from "setter" methods, allowing you to "chain up" method calls.

StringBuilder is one example from the JDK that has a fluent interface. Here's how it works:

int count = 5;
StringBuilder sb = new StringBuilder();
String result = sb.append("The total is ").append(count).append(".").toString(); 

The last line above is equivalent to:

sb.append("The total is ");
sb.append(count);
sb.append(".");
String result = sb.toString();

but results in less, and arguably more readable, code.

The implementations of the various append() methods all return this.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • trying to get some insight on your snippet.. if append() is appending something, why would we expect a returned object? is it just feedback? – James Aug 16 '12 at 15:59
  • i see now.. append() is a method in StringBuilder and the first append() returns 'this' which can be this.append() and so on.. how elegant! – James Aug 16 '12 at 16:05
  • @James I've edited the answer to improve the example to demonstrate it better – Bohemian Aug 16 '12 at 16:10
1

In most cases, when referring to methods or attributes from within a class, this is unnecessary. It however improves readability by making it clear that the variable is stored in the class scope instead of the function scope.

WouterH
  • 1,345
  • 10
  • 16
0

"Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this."

Read here for more info and some examples.

MrHappyAsthma
  • 6,332
  • 9
  • 48
  • 78
0

I don't know who taught you in that way but to my knowledge, this is refrence to the current object.

returnType method(dataType val){
dataType myVariable = someOperation(this.val);
return myVariable;
}

docs.oracle.comsays detail about it.

ln2khanal
  • 949
  • 1
  • 8
  • 16
  • 1
    I guess OP is aware of that. That's not the point of the question. – Qnan Aug 16 '12 at 15:35
  • 1
    **"when an input parameter is the same as the field's name"** I was noticing the line actually @Qnan! – ln2khanal Aug 16 '12 at 15:38
  • I still don't get your meaning. Do you imply that the use case mentioned in the question is not valid? – Qnan Aug 16 '12 at 15:46
  • 1
    The questioner wrote "this" can be useful only when the input parameter and the field's name are same. What I was saying is, it is not only useful in above condition but also for any valid field's name and parameter. Thats the thing I was pointing actually. – ln2khanal Aug 16 '12 at 15:58
  • it was mentioned as one of the cases where `this` is *useful*, not as the only allowed case – Qnan Aug 16 '12 at 16:36