How are Anonymous inner classes used in Java?

后端 未结 18 1397
孤独总比滥情好
孤独总比滥情好 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:50

    They're commonly used as a verbose form of callback.

    I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)

    Here's a swing example

    myButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            // do stuff here...
        }
    });
    

    Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)

提交回复
热议问题