wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes this Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "this" Watch "this" New topic
Author

this

Sohrab Khan
Greenhorn

Joined: Oct 31, 2001
Posts: 3
wat is this in java?
Wilfried LAURENT
Ranch Hand

Joined: Jul 13, 2001
Posts: 269
Quoted from JLS:
"The keyword this denotes a value, that is a reference to the object for which the instance method was invoked (�15.12), or to the object being constructed. "
In other word it stands for the instance of the class.
Example:
public class Toto {
private int t;
Toto(int t) {
this.t=s;
}
/**
Compares an object with the instance of Toto you are applying
the equals message to
*/
public boolean equals(Toto toto) {
boolean b=(this==toto);
return true;
}
}
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
this is a Java keyword that references the current instance of a class. If you don't write "this.someMember" but just "someMember", the compiler is gonna add that for you, but it is good practice to write "this" since it can lead to nasty bugs.
For instance:

Line 1 is bad code, since what we want to do is assign the value of the constructor argument someInt to the member variable someInt. Without "this.", the compiler may think that you are referring to the argument and not the member variable and thus assigns someInt (as argument) to itself. This is definitely not what we want since the member will have the value 0 regardless of the value of the argument of the constructor. Of course, you should choose different names for the argument and the member but sometimes you'll forget.
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Sohrab
You might find the Java tutorial helpful. There is also Bruce Eckel' Thinking in Java which is free to download.

------------------
Dave
Sun Certified Programmer for the Java� 2 Platform


Dave
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: this