java - 用作接口(interface)替代的内部类示例

标签 java actionscript-3 oop interface inner-classes

我被告知,这激发了我对这个话题的好奇:

Java gui classes can implement hundreds of Listeners and Callbacks and many books teach you to implement all these interfaces in your gui class. Alternatively, these aspects can be implemented in inner classes, so methods called by that listeners do not get mixed up.

我想知道如何在没有内部类但有私有(private)类的 ActionScript 中执行此操作。但是,我不认为我完全了解内部类是关于什么的,所以我只是想了解我将使用它们根据用法组织类方法的情况。

请展示一个示例,说明这在 ActionScript 中的外观,如果可能的话,否则在 Java 中。

最佳答案

在java中它看起来像这样:

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

这里 ActionListener - 是一个接口(interface),通过调用 new ActionListener() {/*interfaces method implementations goes here*/}; 你正在创建匿名类(匿名,因为它没有名称)- 该接口(interface)的实现。

或者你可以像这样创建内部类:

 class MyActionListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
      // code that will be performed on any action on this component
   }
 };

然后像这样使用它:

 new JButton().addActionListener(new MyActionListener());

此外,您可以将监听器声明为顶级或静态内部类。但是有时使用匿名内部类非常有用,因为它允许您几乎在声明监听器正在监听的组件的同一位置实现监听器。显然,如果监听器方法代码很长,那将不是一个好主意。那么最好将其移动到非匿名内部或静态嵌套或顶级类中。

通常,内部类是非静态类,它们以某种方式驻留在顶级类的主体中。在这里您可以看到它们在 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();
    }
}

关于java - 用作接口(interface)替代的内部类示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6126636/

相关文章:

javascript - Java 和 Javascript - Lastmodified 在 Linux 上

java - 我应该将 try-catch block 与断言一起使用吗

arrays - 使用对象属性自定义排序数组

actionscript-3 - 将帧同步到音频和 channel.position 精度

php - 我如何知道请求是否来自 flash swf?

php - 如何创建一个全局可访问的对象

python - 如何在 Python 中重构类?

java - JVM 如何对用户的请求使用react

java - 学习 Smali 的最佳方式是什么(以及如何/何时使用 Dalvik VM 操作码)?

java - 面向对象/数字泛型