File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes What's the purpose of Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What Watch "What New topic
Author

What's the purpose of "this" keyword?

Bob Zoloman
Ranch Hand

Joined: Jul 02, 2006
Posts: 72
Can anyone give some simple examples of when to use "this" keyword and why? I sometimes see it used when accessing a classes variables, but you can just access the variables using the variable name, so whats the point of using it?
Sundar Ram
Ranch Hand

Joined: May 22, 2006
Posts: 102
Hi,
"this" keyword is used to refer the current object instance of the class.

Useful Link: http://java.sun.com/docs/books/tutorial/java/javaOO/thiskey.html

-Sundar


SCJP 5.0 | SCWCD 1.4
http://heysundar.blogspot.com
Gaurav Agarwal
Greenhorn

Joined: Oct 13, 2004
Posts: 18
Hi

U can use this keyword when the object varable name is same as methods parameter in that case you can not directly refer to the object varable you have to use this keywords.
Mike Noel
Ranch Hand

Joined: Dec 15, 2005
Posts: 108
I see (and use) "this" a lot in getter and setter methods.


In this case it's a style thing. I could just as easily give my method parameters a different name and then avoid using "this".


Mike Noel
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
The keyworkd this is also useful when you have to reference members of outter classes.

For instance:



The method getInnerName() could have also be coded like this:

1. this.name
2. Outter.Inner.this.name
3. Inner.this.name
[ July 14, 2006: Message edited by: Edwin Dalorzo ]
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61657
    
  67

"Zolo Bob",

There aren't many rules that you need to worry about here on the Ranch, but one that we take very seriously regards the use of proper names. Please take a look at the JavaRanch Naming Policy and adjust your display name to match it.

In particular, your display name must be a first and a last name separated by a space character, and must not be obviously fictitious.

Thanks!
bear
JavaRanch Sheriff


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Bob Zoloman
Ranch Hand

Joined: Jul 02, 2006
Posts: 72
Thanks for the help guys!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What's the purpose of "this" keyword?