• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What's the purpose of "this" keyword?

 
Bob Zoloman
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Gaurav Agarwal
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65120
91
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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
 
Bob Zoloman
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help guys!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic