Java’s Awesome Anonymous Inner Class

My day job has recently forced me to rejoin the Java world.  I prefer C# for many reasons (LINQ!) but I like Java well enough and it’s fun to get all nerdy in a language I don’t spend much time in traditionally.  On the side, I decided to keep the nerdness going with a foray into Android development.  Let it be known: I don’t own an Android device, but I hope to soon.

While I was working on setting up a button in my UI, I googled for some code on setting up the click event-handler.  What I found was this gem:

viewClockButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //do something cool 

What we have here is a smooth use of a handy Java feature, combined with some syntactical coolness.  First off, on the button object, we call the setOnClickListener() method which accepts a parameter of any type that implements the OnClickListener interface.  I have already defined a class of the same name with this code:

public class OnClickListener implements android.view.View.OnClickListener {

    public void onClick(View arg0) {

        // TODO Auto-generated method stub



In the original call to setOnClickListener(), I instantiate a new object of type OnClickListener, but then I do something special.  I open up squiggly braces and then override the onClick() method with custom behavior just for this button’s click event.

What this looks like: It looks like I’m creating a new object, and then dynamically injecting custom behavior into one of it’s methods, so that THIS instance of class OnClickListener will have different behavior from other instances.  This is somewhat common in dynamic languages like Ruby and Javascript.

What is actually happening:  When I open the squiggly brace after instantiating the object, I’m actually creating a new anonymous inner class, which inherits from OnClickListener, and then overrides the behavior of the onClick() method.

This is pretty cool.  I would love to be able to use similar syntax to pull off this type of thing in C#, but then again in C# I have full access to lambdas, delegates, Func<>’s, and all sorts of ways to achieve the same ultimate desired behavior.  Still, I can’t help but like this, both for it’s syntax and it’s under-the-hood power.

Original source:


One Response to “Java’s Awesome Anonymous Inner Class”

  1. Book of Shadows Says:

    thanks alot man, this will deff help in my next release

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: