Is usage of anonymous classes in Java considered bad style or good?

后端 未结 14 1287
Happy的楠姐
Happy的楠姐 2020-12-05 01:58

I know anonymous classes save typing when it comes to implementing Listener and similar stuff. They try to be a replacement for some usages of closures.

But what doe

14条回答
  •  执念已碎
    2020-12-05 02:59

    One more good use of anonymous inner class is when you need to initialize collections like ArrayList and Set. This practice is also known as double brace initialization For example ,

    private static final Set VALID_CODES = new HashSet() {{
    add("XZ13s");
    add("AB21/X");
    add("YYLEX");
    add("AR2D");
    }};
    

    Obviously, this is not limited to collections; it can be used to initialize any kind of object -- for example Gui objects:

     add(new JPanel() {{
    setLayout(...);
    setBorder(...);
    add(new JLabel(...));
    add(new JSpinner(...));
    }});
    

提交回复
热议问题