In java, it looks like this:
new JButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // code that will be performed on any action on this component } };
here the ActionListener is the interface, and by calling new ActionListener() {/*interfaces method implementations goes here*/}; , you create an anonymous class (anonymous, because it does not have a name) - an implementation of this interface.
Or you can make an inner class as follows:
class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { // code that will be performed on any action on this component } };
and then use it like this:
new JButton().addActionListener(new MyActionListener());
In addition, you can declare your listener as a top or static inner class. But using an anonymous inner class is sometimes very useful, because it allows you to implement your listener almost in the same place where the component that declares listening to your listener is declared. Obviously, it would not be a good idea if the code of the listener methods is very long. Then it would be better to move it to a non-anonymous internal or static nested or top level.
In general, inner classes are non-static classes that somehow reside inside the body of a top-level class. Here you can see examples of them in Java:
//File TopClass.java class TopClass { class InnerClass { } static class StaticNestedClass { } interface Fooable { } public void foo() { new Fooable(){}; //anonymous class class LocalClass { } } public static void main(String... args) { new TopClass(); } }
dhblah
source share