• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

this

 
Sohrab Khan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wat is this in java?
 
Wilfried LAURENT
Ranch Hand
Posts: 269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic