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 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.
I'd like to know how to do this in ActionScript, which doesn't have inner classes, but has private classes. But, I don't think I fully realize what inner classes are about, so I'm merely trying to wrap my head around the situation where I would use them to organize a class' methods by their usages.
Please show an example of how this would look in ActionScript, if possible, otherwise Java.
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();
}
}
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