Double Brace Initialization in Java

It is a subtle use of two basic java conceptions. First, we can create an anonymous inner class in time of class instantiation, syntax for which is usual

new Person(){};

Remember we are not exactly creating an object of Person rather we are creating an object of anonyms subclass.

Then we can define any number of initializer block in a class [Official Doc]. Syntax for that is

class Person {
    {
        System.out.println("In an initializer block");
    }
}

Bingo! Lets combine them both we get the double brace initialization

new Person(){{
    //do anything with this subclass of person
}};

Common use:

new ArrayList<String>(){{
    add("First Element");
    add("Second Element");
    add("Third Element");
}};

If you have some background of using ruby, perl or any language that provides mechanism of passing method block or lambda function then you will like it. But just one caveat, java creates a separate *.class file for each class. So each time a double brace initialization is used, it creates a separate *.class file. Yeah! you guessed it right. If you initialize 5 arrays such way in a Main.java you are going to get Main.class, Main$1.class, Main$2.class up to Main$5.class. Just prepare for this surprise in target/classes folder, if you plan to ever visit your build directory 😉

Advertisements

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