Sign in to follow this  

Android & Java language question

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I have a question about an example given at: [url=http://developer.android.com/reference/android/app/Service.html#LocalServiceSample]Service | Android Developers[/url]
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++.

[CODE]

private LocalService mBoundService;

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


[/CODE]

Share this post


Link to post
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 this post


Link to post
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".

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this