Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In java it looks like that:</p> <pre><code> new JButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // code that will be performed on any action on this component } }; </code></pre> <p>here <code>ActionListener</code> - is an interface, and by calling <code>new ActionListener() {/*interfaces method implementations goes here*/};</code> you're creating anonymous class (anonymous because it has no name) - implementation of that interface.</p> <p>Or you can make inner class like this:</p> <pre><code> class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { // code that will be performed on any action on this component } }; </code></pre> <p>and then use it like this:</p> <pre><code> new JButton().addActionListener(new MyActionListener()); </code></pre> <p>Moreover you can declare your listener as a top-level or static inner class. But using anonymous inner class sometimes is very useful because it allows you to implement your listener almost in the same place where the component which actions your listener is listening to is declared. Obviously it won't be a good idea if the listeners methods code is very long. Then it would be better to move it into a non-anonymous inner or static nested or top-level class.</p> <p>In general, innner classes are non-static classes that somehow resides inside the body of the top-level class. Here you can see examples of them in Java:</p> <pre><code>//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(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload