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 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

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
"this" keyword is used to refer the current object instance of the class.

Useful Link:


SCJP 5.0 | SCWCD 1.4
Gaurav Agarwal

Joined: Oct 13, 2004
Posts: 18

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:

[ July 14, 2006: Message edited by: Edwin Dalorzo ]
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63841

"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.

JavaRanch Sheriff

[Asking smart questions] [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:
subject: What's the purpose of "this" keyword?
It's not a secret anymore!