Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it clearer to always use "this" or only when necessary? [duplicate]

Tags:

java

Possible Duplicate:
Java - when to use 'this' keyword

Some developers like to always use "this" when referring to an object's methods and properties, even when it isn't needed. Here's a really simple example:

public class Foo {

    private String id;

    public Foo() {
        this.id = "123456789";
    }

}

Is it clearer to always use "this" or only when it is necessary? Are there any cases in which you should always use it?

like image 358
Chris Bui Avatar asked May 10 '11 01:05

Chris Bui


People also ask

Should we always use this in Java?

In answer to "Are there any cases where you should always use this ?" You should use it when it is needed to avoid ambiguity, for example if there is another variable with the same name in scope.

When should you use this Keyword?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

Does Java use this?

this Keyword in Java is a reference variable that refers to the current object. this in Java is a reference to the current object, whose method is being called upon. You can use “this” keyword to avoid naming conflicts in the method/constructor of your instance/object.


1 Answers

It make no difference in the generated code. So use is up to company development guidelines or personal preference.

It can help identify what is a member variable and what is not, it also help to use this-> as the ide or editor can do better code completion (depending on the age of the editor).

like image 198
Gregor Brandt Avatar answered Oct 13 '22 14:10

Gregor Brandt