-->

Block Statements in Java

2019-02-22 01:28发布

问题:

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");
};

回答1:

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.



回答2:

What you're actually doing here is define an anynomous subclass of MyMap, which was probably not your intent... The outermost curly braces are around the class contents. And in Java, you cannot put instructions directly inside a class block: if you need code to be executed when the class is instantiated, you put it into a constructor. That's what the innermost braces are for: they delimit an initializer for your anonymous class.

Now, you probably wanted something like:

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

Just create an instance of MyMap and call put on it, no anonymous class involved.



标签: java block