Example of inner classes used as an alternative to interfaces

后端 未结 2 1242
臣服心动
臣服心动 2020-12-30 12:00

What I was told, which sparked my curiosity on this topic:

Java gui classes can implement hundreds of Listeners and Callbacks and many books teach you

相关标签:
2条回答
  • 2020-12-30 12:40

    Gasan gives an excellent example of how inner classes are typically used for callbacks in Java GUIs. But in AS3 you would not normally do it this way, because AS3 event listeners are function references, not interfaces. In this respect, AS3 has more in common with JavaScript than Java.

    What you can do in AS3 (just as with JavaScript) in place of the anonymous inner class callbacks is create function closures.

    EDIT: I found a reference here that saves me a lot of typing:

    ActionScript 3.0 using closures for event handlers

    0 讨论(0)
  • 2020-12-30 13:00

    In java it looks like that:

      new JButton().addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
              // code that will be performed on any action on this component
          }
      };
    

    here ActionListener - is an interface, and by calling new ActionListener() {/*interfaces method implementations goes here*/}; you're creating anonymous class (anonymous because it has no name) - implementation of that interface.

    Or you can make inner class like this:

     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());
    

    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.

    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:

    //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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题