How are Anonymous inner classes used in Java?

后端 未结 18 1368
孤独总比滥情好
孤独总比滥情好 2020-11-21 05:19

What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?

18条回答
  •  囚心锁ツ
    2020-11-21 05:54

    I use them sometimes as a syntax hack for Map instantiation:

    Map map = new HashMap() {{
       put("key", "value");
    }};
    

    vs

    Map map = new HashMap();
    map.put("key", "value");
    

    It saves some redundancy when doing a lot of put statements. However, I have also run into problems doing this when the outer class needs to be serialized via remoting.

提交回复
热议问题