Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "this" with methods (in Java)

Tags:

java

methods

this

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;
    }
}
like image 241
user42155 Avatar asked Feb 05 '09 16:02

user42155


People also ask

Can you use this in a method Java?

The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Yes, you can call methods using it.

How do you use this in method?

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 .

Can we use this keyword in main method in Java?

Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method. If you still, try to do so a compile time error is generated. And main method is static therefore, you cannot use the "this" reference in main method.

Can we return this keyword from a method in Java?

Returning “this”Yes, you can return this in Java i.e. The following statement is valid. return this; When you return "this" from a method the current object will be returned.


4 Answers

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

like image 26
Yes - that Jake. Avatar answered Oct 05 '22 22:10

Yes - that Jake.


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.

like image 170
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet


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.

like image 35
Mike Avatar answered Oct 06 '22 00:10

Mike


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.

like image 22
Steve Kuo Avatar answered Oct 06 '22 00:10

Steve Kuo