Example of inner classes used as an alternative to interfaces

后端 未结 2 1241
臣服心动
臣服心动 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 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();
        }
    }
    

提交回复
热议问题