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);
About these ads

Leave a Reply


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

Twitter picture


Facebook photo


Google+ photo


Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: