Skip to content
3 May 2012 / parroit

Anonymous Instance Constructor

What are anonymous constructor? All we knows standard java constructor, that allow us to create new object instances.

Java also allow us to declare static constructor, that are able to initialize static class fields, and that get called the first time our class is created by the VM.

static class StaticExample{
    private static final String someStaticThing;
        static {
            someStaticThing = "Some Thing";

A less known feature is that Java also has anonymous constructors. Their syntax is very similar to that of static constructor, with the difference that they execute on every object instances creation, instead of on class creation:

class AnonymousExample{
    private final String something;
       this.something = "Some Anonymous Thing";

So far, so good, very simple… But what they can be useful for? After all we already have normal constructors, that has the non indifferent advantage that

they can accept parameters, a thing that we can’t do with anonymous constructors.

Well, they can be useful in a lot of cases. The first I can imagine is the developing of “swing builders”. Take the following trivial Swing code:

void buildUI(){
    JDialog simpleMessage=new JDialog();
    JLabel label=new JLabel("A simple message for you");
    simpleMessage.setLayout(new BorderLayout());
    simpleMessage.setSize(new Dimension(400,100));

Simple and clear, but not very concise… If we use Scala or Groovy, the same code could take advantage of the use of anonymous inner classes. Using anonymous constructor, we can improve the code style also in plain old Java.

Anonymous constructors could be used also in anonymous classes, thta in Java cannot take constructors. By leveraging this feature, we can rewrite the preceding code in the following way, improving code conciseness and readability:

JDialog simpleMessage=new JDialog(){{
    setLayout(new BorderLayout());
    setSize(new Dimension(400, 100));
    add(new JLabel(){{
        setText("A simple message for you");
    }}, BorderLayout.CENTER);

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: