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");
    label.setBackground(Color.gray);
    label.setForeground(Color.red);
    label.setHorizontalAlignment(SwingConstants.CENTER);
    label.setFont(label.getFont().deriveFont(26.0f));
    simpleMessage.setLayout(new BorderLayout());
    simpleMessage.add(label,BorderLayout.CENTER);
    simpleMessage.setSize(new Dimension(400,100));
    simpleMessage.setModal(true);
    simpleMessage.setVisible(true);
}

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));
    setModal(true);
    add(new JLabel(){{
        setText("A simple message for you");
        setBackground(Color.gray);
        setForeground(Color.red);
        setHorizontalAlignment(SwingConstants.CENTER);
        setFont(getFont().deriveFont(26.0f));
    }}, BorderLayout.CENTER);
}};
simpleMessage.setVisible(true);
About these ads

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: