Except the original question is about "this" and why it works to use it as an argument. My comments explain why the this is missing when an event handler is called.

I apologize that I don't know what the Java term is that corresponds with the C++ term static, but in C++ the this pointer is the only difference between a static and a non-static function. Providing the this pointer in C++ as an argument for a static function allows the event handler to do everything that a non-static function does except the static function must use the this pointer to qualify references to the class.

Perhaps I misunderstand what you are saying; are you saying that it is possible to pass something else in the argument other than the this reference? If so then that is not inconsistent with what I said or meant to say, but the question was about the this reference.


DanH wrote:
Well, that's not exactly it.  The pointer is needed in
setOnClickListener to distinguish that specific instance of the
listener class from the thousand other possible instances in the
machine.  You'll find the analogous pointer in C++ based systems, eg.

And note that it need not be "this".  One might very well do:

MyListenerClass listener = new MyListenerClass(<some args>);
someWidget.setOnClickListener(listener);

On Jul 18, 4:53 pm, Sam Hobbs<[email protected]>  wrote:
I am new to Java, but since Justin says that the this reference is
essentially the same as in C++ and C# I hope my comments are helpful.

I think one point that was not made clear is that the operating system
(Android, Linux or whatever) is not written in Java but if it was
written in Java it would need to call event handlers in a manner that is
independent of the language. So when Android calls the
setOnClickListener event handler, it does not have a this reference and
could not call the event handler with this even if it knew what this is.
So it is quite common to pass the this as an argument so the event
handler can access the other members of it's class.

Keith Roberts wrote:
Hey all,

I know that the keyword "this" refers to an instance variable or can
invoke a constructor, but I don't understand how passing "this" as the
arg for setOnClickListener () works?Could someone explain?

Thanks,

keith

--
Sam Hobbs
Los Angeles, CA


--
Sam Hobbs
Los Angeles, CA

--
You received this message because you are subscribed to the Google
Groups "Android Beginners" group.

NEW! Try asking and tagging your question on Stack Overflow at
http://stackoverflow.com/questions/tagged/android

To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-beginners?hl=en

Reply via email to