\$25

### Image of the Day Submit

IOTD | Top Screenshots

## Android & Java language question

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

4 replies to this topic

### #1totesmagotes  Members

Posted 07 May 2012 - 02:06 PM

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) {
......
}
};



### #2totesmagotes  Members

Posted 07 May 2012 - 02:33 PM

OK, so turns out this is an anonymous inner class.

### #3SriLumpa  Members

Posted 07 May 2012 - 02:33 PM

It is called an "anonymous class", I think.

### #4MESEnterprisesLLC  Members

Posted 08 May 2012 - 08:16 AM

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

### #5Zul  Members

Posted 11 May 2012 - 01:50 PM

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

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.