Android & Java language question

This topic is 2263 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hello, I have a question about an example given at: Service | Android Developers
I don't think you need to know anything about Android to be able to answer this question.
What the heck is going on here? I've never seen syntax like this before, but nowadays I see it all the time in Android examples.

It looks like a new ServiceConnection is being made, but then, instead of ending with a semicolon, we've got braces and then 2 function definitions (overriding the 2 abstract ServiceConnection functions) This must be some special feature of Java I've never seen before, can someone tell me what this feature is called so I can read more about it? I know you can't do this in C++.

 private LocalService mBoundService; private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { ...... ....... } public void onServiceDisconnected(ComponentName className) { ...... } }; 

Share on other sites
OK, so turns out this is an anonymous inner class.

Share on other sites
It is called an "anonymous class", I think.

Share on other sites
Overloading methods in Java when you instantiate an object isn't something new, nor is it something that only occurs in Android apps... As you will notice, the instantiation IS ended with a semi-colon... where you see the };

Anonymous classes, are good for those cases where you need to overload a method or two for a specific situation - if you overload the methods more than once, for the same purpose more than once, then anonymous classes are not recommended.

In any case, it looks like you figured it out.

Share on other sites
Just remember that anonymous classes tend to be harder to debug, especially if you use a lot of them. Getting an error message like "Error in {misc}" can be a lot more frustrating than "Error in Foo".

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 14
• 30
• 13
• 11
• 11
• Forum Statistics

• Total Topics
631781
• Total Posts
3002319
×