20

what about using "this" with methods in Java? Is it optional or there are situations when one needs to use it obligatory?

The only situation I have encountered is when in the class you invoke a method within a method. But it is optional. Here is a silly example just to show what I mean:

public class Test {

    String s;

    private String hey() {
        return s;
    }

    public String getS(){
        String sm = this.hey();
        // here I could just write hey(); without this
        return sm;
    }
}
royhowie
  • 11,075
  • 14
  • 50
  • 67
user42155
  • 48,965
  • 27
  • 59
  • 60
  • Um, I suggested closing based on http://stackoverflow.com/questions/516291/the-use-of-this-in-java but I no longer think they're close enough. – Jon Skeet Feb 05 '09 at 16:53
  • I have understood what "this" mean -a single "this" can be used if you want to refer to the whole current instance of the object, or any element of the object, i.e this.instanceVar.But sometimes you need to use "this" - in the constructor, if the argument is the same: this.var = var.But for methods? – user42155 Feb 05 '09 at 17:02
  • I've updated my answer to show where it might be necessary in a method too, for exactly the same reason. Changing parameter names removes the need for this, however. – Jon Skeet Feb 05 '09 at 17:03

7 Answers7

38

Three obvious situations where you need it:

  • Calling another constructor in the same class as the first part of your constructor
  • Differentiating between a local variable and an instance variable (whether in the constructor or any other method)
  • Passing a reference to the current object to another method

Here's an example of all three:

public class Test
{
    int x;

    public Test(int x)
    {
        this.x = x;
    }

    public Test()
    {
        this(10);
    }

    public void foo()
    {
        Helper.doSomethingWith(this);
    }

    public void setX(int x)
    {
        this.x = x;
    }
}

I believe there are also some weird situations using inner classes where you need super.this.x but they should be avoided as hugely obscure, IMO :)

EDIT: I can't think of any examples why you'd want it for a straight this.foo() method call.

EDIT: saua contributed this on the matter of obscure inner class examples:

I think the obscure case is: OuterClass.this.foo() when accessing foo() of the outer class from the code in an Inner class that has a foo() method as well.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • A newer use case is to create a method reference using `this` instance, e.g., `Runnable r = this::foo;`. – shmosel Oct 10 '17 at 02:03
5

I use "this" to clarify code, often as a hint that I'm calling an instance method rather than accessing a class-level method or a field.

But no. Unless disambiguation is required due to scope naming collision, you don't actually need "this."

Yes - that Jake.
  • 16,725
  • 14
  • 70
  • 96
  • How does "this" clarify if you're calling an instance or class method? Both are legal. – Steve Kuo Feb 05 '09 at 17:40
  • It's a hint--a coding construct given additional meaning by consistent or standardized use under more constrained circumstances than are legal. – Yes - that Jake. Feb 05 '09 at 19:18
  • But "this" will work for static methods, instance methods, and super's methods, so unless someone knows your specific hint rules, it's absolutely unless. Actually it makes your code even harder to understand. – Steve Kuo Feb 11 '09 at 21:51
3

For most general programing, the this keyword is optional and generally used to avoid confusion. However, there are a few places where it is needed.

class Foo {
    int val;

    public Foo(int val) {
         this(val, 0);  //this MUST be here to refer to another constructor
    }

    public Foo(int val, int another) {
        val = val;       //this will work, but it generally not recommended.
        this.val = val;  //both are the same, but this is more useful.
        method1();       //in a Foo instance, it will refer to this.method1()
        this.method1();  //but in a Foo2 instance, you must use this to do the same
    }

    public void method1() {}
}

class Foo2 extends Foo {
    public Foo2(int val) {
        this(val);        //this will refer to the other Foo2 constructor
    }
    public Foo2(int val, int another) {
        super(val, another);
        super.method1();   //this will refer to Foo.method1()
    }

    @Override
    public void method1() {}//overridden method
}

These are not all the cases, but some of the more general ones. I hope this helps you better understand the this and super keywords and how/when to use them.

Denis Tsoi
  • 9,428
  • 8
  • 37
  • 56
Mike
  • 3,219
  • 23
  • 29
  • this.method1() will call method1() of the class type, so adding "this" doesn't make any difference. – Steve Kuo Feb 05 '09 at 17:42
  • 2
    Btw, as other people commented above, having val = val; in the constructor in this example, will not give the desired effect. The program compiles, but the instance variable will never be initialised in the constructor. It will always be 0 - from the default constructor. – user42155 Feb 05 '09 at 17:46
  • Is the Foot() method supposed to be Foo()? – Logan Aug 29 '18 at 17:00
2

The only reason to prepend this in front of a method invocation is to indicate that you're calling a non-static method. I can't think of any other valid reason to do this (correct me I'm wrong). I don't recommend this convention as it doesn't add much value. If not applied consistently then it could be misleading (as a this-less method invocation could still be a non-static method). How often does one care if the method being invoked is static or not? Furthermore, most IDEs will highlight static methods differently.

I have heard of conventions where this indicates calling the subclass's method while an absence of this is calling the super class's method. But this is just silly as the convention could be the other way around.

Edit: As mmyers points out (see comment), this works with static methods. With that, I see absolutely no reason to prepend with this as it doesn't make any difference.

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
0

The only time it is really required is when you have a parameter to a method with the same name as a member variable. Personally, I try to always use it to make the scope of the variable/method explicit. For example you could have a static method or an instance method. When reading the code it can be helpful to know which is which.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
0

Not an answer (so feel free to vote it down), but I couldn't fit this into a comment where someone was asking.

A lot of people use "this.x" to visually differentiate instance variables from local variables and parameters.

So they would do this:

private int sum;
public int storeSquare (int b) {
    int c=b*b;
    this.sum+=c; // Makes sum "pop" I guess
    return c;
}

Personally I think it's a bad habit: any usable editor will put instance and local variables in a different color for you reliably--it doesn't require any human-fallible patterns.

Doing it with "this." is only 50% safe. Sure the compiler will catch it if you try to put this.x when x is a local variable, but there is nothing that is going to stop you from "Forgetting" to tag an instance variable with this., and if you forget to tag just one (or if someone else works on your code) and you are relying on the pattern, then the pattern may be more damaging than good

Personally I'm fairly sure the pattern stems from programmers (rightful) discomfort with the fact that in this case:

public void setMe(int me) {
    this.me=me;
}

the fact that you need "this." in front of the me is determined by the name of the parameter--I agree it just feels sloppy. You want to be consistent--if you need this. in front of the me there, why not always use it?

Although I understand the discomfort, typing this. every single place that an instance variable is used is just pedantic, pointless, ugly and unreliable. If it really bothers you and you absolutely need to use a pattern to solve it, try the habit of putting "p" in front of your parameters. As a side effect, it should even make it more constant because the parameter case will now match the method case..

public void setMe( int pMe) 
Bill K
  • 62,186
  • 18
  • 105
  • 157
0

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html

You absolutely need this if your method needs to return the object's instance.

public class StringBuildable {
    public StringBuildable append(String text) {
        // Code to insert the string -- previously this.internalAppend(text);
        return this;
    }
}

This allows you to chain methods together in the following fashion:

String string = new StringBuildable()
    .append("hello")
    .append(' ')
    .append.("World")
    .toString()
;
Emmanuel Rodriguez
  • 1,584
  • 10
  • 9
  • That doesn't really answer the question. It's more geared towards http://stackoverflow.com/questions/516291/the-use-of-this-in-java. – Michael Myers Feb 11 '09 at 20:09
  • One of the questions was: "Is [this] optional or there are situations when one needs to use it obligatory?". I do believe that I've showed an example where it is obligatory. If you want to return an instance of the object in a method you must use "this". – Emmanuel Rodriguez Feb 11 '09 at 20:48
  • I fail to see why "this" is required in your example. "this.internalAppend(text);" can be replaced by "internalAppend(text);". – Steve Kuo Feb 11 '09 at 22:00
  • @Steve you are right that "this.internalAppend(text);" (that was made an omission by me, I always prefix this to all method calls) but the aim of my post was to show where this is required and here it is required at return statement. – Emmanuel Rodriguez Feb 12 '09 at 07:02
  • What value is gained by putting "this" in front of your method calls? – Steve Kuo Feb 13 '09 at 00:41
  • @Steve in theory code clarity see the answer of @Jekke for more details. I say in theory because nothing is preventing you from using this with a static function. – Emmanuel Rodriguez Feb 13 '09 at 06:34