Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to use "this" in java? [duplicate]

As far as I know this is used in following situations:

  1. this keyword is used when we want to refer to instance variable having same name as local variable.
  2. Calling one constructor to other in same class.
  3. Pass the class instance as an argument to the method.
  4. Accessing the outer class variables.

But I have gone through my project code where they are using this in getters like:

class a {
    int time;

    int getValue() {
        return this.time * 5.;
    }
}

As far as I know, every object has its own copy of instance variables and methods, so will returning this way makes any sense. Please clarify.

Stackoverfow problem referred:When should I use "this" in a class?

like image 610
mahan07 Avatar asked May 27 '15 17:05

mahan07


2 Answers

Many people (I'm one of them) use this keywords even when it is not explicitely needed.

  • Some people find it more clear to put this in front of anything which belong in the same class, the same logic apply to super.
  • Some people always use this by reflex for a better auto-completion (pop-up appear automatically, lazy programmer) in some IDE.

These points are mostly opinion based and doesn't really matter.

For the other uses, as you mentionned, it can be used to pass parameter to another constructor, pass the class instance or to distinct when you have two variables with the same name.

However, IMO, it is way simplier to just not have multiple variables with the same name.

like image 95
Jean-François Savard Avatar answered Sep 30 '22 17:09

Jean-François Savard


When you have a method like the following one:

public void setFoo(Foo foo) {
    this.foo = foo;
}

Using this is mandatory. Otherwise, it would assign the argument foo to itself, instead of assigning it to the instance variable.

But that doesn't mean that's the only situation you may use this. The following code is strictly equivalent:

public void setFoo(Foo newFoo) {
    this.foo = newFoo;
}

Although in that case, you might very well write

public void setFoo(Foo newFoo) {
    foo = newFoo;
}

because this is not necessary anymore. That doesn't make it illegal.

So,

int getValue() {
    return time * 5;
}

and

int getValue() {
    return this.time * 5;
} 

are strictly equivalent.

like image 21
JB Nizet Avatar answered Sep 30 '22 17:09

JB Nizet