Hi all,
Can some one post an example stating the use and benefit this keyword in java?
Thanks in advance...
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Mahesh ChandPosted Jul 14, 2011, 10:01 PM
Sam HobbsPosted Jul 14, 2011, 9:55 PM
A "this" is also "me" for an object. When used with an object, "this" refers to the object; to itself. So if you have a class called "House" then there might be instances of House for John and for Mahesh. If you use the instance for House that is for John then within that instance this.City might be "New York" and if you use the instance for House that is for Mahesh then within that instance the city might be "Mumbai".
VulpesPosted Jul 14, 2011, 6:53 AM
It is often used to distinguish between the fields of a class and the local variables or parameters of a method within that class.
For example:
public class Point
{
public int x = 0;
public int y = 0;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
Jaganathan BantheswaranPosted Jul 14, 2011, 6:49 AM
Java's 'this' keyword is used to refer the current instance of the method on which it is used.
Following are the ways to use this
1) To specifically denote that the instance variable is used instead of static or local variable.That is,
private String jaQ;
void methodName(String jaQ) {
this.jaQ = jaQ;
}
Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the "this" denotes the local variable. If the local variable that is parameter's name is not same as instance variable then irrespective of this is used or not it denotes the instance variable.
2) This is used to refer the constructors
public Jas(String ja) {
this(ja, true);
}
This invokes the constructor of the same java class which has two parameters.
3) This is used to pass the current java instance as parameter
obj.itIsMe(this);
4) Similar to the above this can also be used to return the current instance
CurrentClassName startMethod() {
return this;
}
Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.
5) This can be used to get the handle of the current class
Class className = this.getClass(); // this methodology is preferable in java
Though this can be done by, Class className = ABC.class; // here ABC refers to the class name and you need to know that!
As always, this is associated with its instance and this will not work in static methods.