Block Statements in Java

后端 未结 2 747
半阙折子戏
半阙折子戏 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

    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.

提交回复
热议问题