• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can someone explain "this"?  RSS feed

 
Nilesh Srivastava
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please explain id detail what is "this" object?
Where is this used and how is this different from the original object name.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "this" object is the object that is running the method. It is available in all Java methods except static ones. However, where it is available, it is usually optional -- you need not use it when calling other methods in the same object (but you can), but you must use it when trying to pass the current object as an explicit parameter to some method. (Although I always put it in for clarity, but then that's just me. Others think the code clearer without the "this"es.)
Say you had the following class:

The showMessage method takes one parameter, right? That's how we talk about it, because that's just how it looks to you -- there is one explicit parameter. But, behind the scenes, there is another, implied, parameter: the "this" object. If you were to translate this method to what it actually functions like, it would look like:

So where does the "this" argument come from? It is the object on which the method was invoked. When you say:

What you are actually doing is saying:

And in the method, anInstance object is referenced by the name "this" jsut as the "Hello, World" string is referenced by the name "msg".
Hope this clears up any confusion,
[ September 03, 2003: Message edited by: Joel McNary ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you're writing a method, sometimes you need to refer to the method the object was called on. You use "this" for that purpose.
Say, for example, that an object wants to store itself in a Vector. You might write

Now, some other code might call this method:
 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent Expalnations.....gurus.
 
Nilesh Srivastava
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Joel,
I do agree with Matthews.
U explained the "this" object in a splendid way.
Thanks a lot to u all
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!