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?
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.
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).
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With