Block Statements in Java

后端 未结 2 751
半阙折子戏
半阙折子戏 2021-01-18 04:39

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

<         


        
2条回答
  •  执念已碎
    2021-01-18 05:14

    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.

提交回复
热议问题