Android & Java language question

Started by
3 comments, last by Zul 11 years, 11 months ago
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) {
......
}
};


Advertisement
OK, so turns out this is an anonymous inner class.
It is called an "anonymous class", I think.
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.
Michael Suess
MES Enterprises, LLC
http://mesenterprisesllc.com
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".
oh hai

This topic is closed to new replies.

Advertisement