File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "this" Watch "this" New topic


Sohrab Khan

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.
public class Toto {
private int t;
Toto(int t) {
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

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.
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform

[Blog] [Blogroll] [My Reviews] My Linked In
Dave Vick
Ranch Hand

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

Sun Certified Programmer for the Java� 2 Platform

I agree. Here's the link:
subject: this
It's not a secret anymore!