Search code examples
javablock

Block Statements in Java


I have a class MyMap which extends java.util.HashMap, the following code works as a block of statements but I don't understand the use of the extra curly braces

MyMap m = new MyMap() {
  {
      put("some key", "some value");
  }
};

Now why do I need the extra curly braces, can't I just do this (but this raises compile error)

MyMap m = new MyMap() {
    put("some key", "some value");
};

Solution

  • This:

    MyMap m = new MyMap() {
        ....
    };
    

    creates an anonymous inner class, which is a subclass of HashMap.

    This:

    {
        put("some key", "some value");
    }
    

    is an instance initializer. The code is executed when the instance of the anonymous subclass is created.