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

后端 未结 14 1281
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<String> VALID_CODES = new HashSet<String>() {{
    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(...));
    }});
    
    0 讨论(0)
  • 2020-12-05 02:59

    We use anonymous classes regurlarly. I find them easy to use for implementing interfaces that have only one or two methods and that where the functionality isn't used anywhere else. If you use the same functionality again somewhere else there should be a real class to be reused.

    0 讨论(0)
提交回复
热议问题