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
Related
Can someone explain this Java syntax to me?
What are those brackets doing inside the outer parentheses?
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
It's called an anonymous inner class. It creates an unnamed class that extends WindowAdapter (it would also have been possible to specify an interface, in which case the class would implement that interface), and creates one instance of that class. Inside the brackets, you must implement all abstract methods or all interface methods, and you can override methods too.
This is an anonymous inner class -- the brackets denote the beginning and ending of the class declaration. This is a potentially useful SO question, and a bunch of others.
And to complement andersoj's answer, you usually use them when a method expects an instance of X, but X is an abstract class or an interface.
Here, you're actually creating a derived class from WindowAdapter, and overriding one of the methods to do a specific task.
This syntax is very common for event handlers / listeners.
It is an anonymous inner class. It is just a shortcut. You can imagine how the code would look like if you needed to create it as a top level class:
class CloseApplicationWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
Then, inside your code you would do:
CloseApplicationWindowAdapter adapter = new CloseApplicationWindowAdapter();
addWindowListener(adapter);
Both solutions have exactly the same effect (althoug the anonymous class would create a Class$1.class file, for instance). Java programmers will often prefer the anonymous class approach if the anonymous class does not get too big/complicated/important.
I am new to java and stackoverflow
I have
class Assemble()
class Start()
class Ignite()
class Move()
...... There are still 12 classes
I want use methods inside these classes
but
i should not create objects of them
i cannot use extends for all these also
i there any way possible?
Please bare anything silly, i am not able to figure out.
And this is my first question hear.
the finaly class is
class run
{
public void run_simple()
{
// hear i should be able to access all methods of above class
}
}
If you use an object oriented language (as java) the way it is meant, your whole program is about creating and using objects (as mentioned in many comments). There are some valid technical reasons not to create objects and to use static methods ("it's tedious" is not one of them). There are environments that forbid to use inheritance.
Please state these reasons, otherwise we have to assume that you don't understand some basic concepts of object oriented languages and that your "restrictions" must be ignored.
Most "restrictions" of object oriented programming are intended to help you structure your solution/program. If you see them as real restrictions, the structure of your program might very well be bad.
I'd like to give an example on how something like this might look "the OO way". This might not fully match your project, but should show you that creating objects must not be an issue programmer effort wise.
First we need an interface that defines what one of your actions (thats what I call your classes) looks like
interface Action {
public void run();
}
The following classes define the concrete actions. Their constructors might take parameters configuring details on how to execute them. In the run()-method of each class, you program on what an action does when executed.
class Assemble implements Action {
public void run() {...}
}
class Start implements Action {...}
class Ignite implements Action {...}
class Move implements Action {...}
The controller does the "run everything". That's basically your "overhead" for creating objects!
class Controller {
/** Returns a list of the configured action objects. */
public static List<Action> buildActions() {
List<Action> actions = new LinkedList<Action>();
actions.add(new Assemble(parameter)); // or whathever parameters you need
actions.add(new Start(parameter1, parameter2));
actions.add(new Ignite());
actions.add(new Move());
}
/** Build the list of actions and run one after the other. */
public static void main(String[] args) {
List<Action> actions = buildActions();
for (Action action: actions) {
action.run();
// here you could add logging, profiling etc. per Action.
}
}
}
I'm new to java. What is the purpose of a listener anonymous inner class design? I heard that anonymous classes are used as listeners in java. And that no one really creates inner classes or even static inner classes. I'm not sure what that means. could some one explain these concepts a bit? Especially this listener design and how its created via an anonymous class.
Thank you in advance.
An anonymous listener would usually look something like this:
myControl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Handle event
}
});
Using an inner class to accomplish the same goal would usually look something like this:
public void init()
{
myControl.addActionListener(new MyActionListener());
}
private class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// Handle event
}
}
Now consider what the two would look like in the scope of a much larger program. The anonymous listener is still right there at the spot where you're adding it. The inner class may be somewhere else in the source file entirely. With a good IDE, that difference can be minimized (such as a members browser), but is there really a need for an entirely new class for something you're going to use once?
Of course, depending on the exact needs of your application, a separate class might in fact be a better choice. If, for example, you have many listeners that differ only a little bit, you could construct something along these lines:
public void init()
{
myControl1.addActionListener(new MyActionListener("foo"));
myControl2.addActionListener(new MyActionListener("bar"));
myControl3.addActionListener(new MyActionListener("baz"));
}
private class MyActionListener implements ActionListener
{
private String word;
public MyActionListener(String word)
{
this.word = word;
}
public void actionPerformed(ActionEvent e)
{
// Handle event
System.out.println(word);
}
}
As far as static classes go: in Java, an inner class can be marked static, and all this does is prevent it from having a reference to the instance of the enclosing class. (For example, MyProgram.MyStaticClass would not be able to access any members of MyProgram which weren't static, unless it creates a new instance of MyProgram.) This may help with separation-of-concerns, but doesn't change very much when it comes to listeners.
That's not true, that no one creates named classes to handle events. Yet most of the time event handlers actually are anonymous classes. The reason for that is that anonymous classes offer less code and less files to maintain and it's easier to read a code when you don't have to jump between many small files. Anonymous classes shouldn't be too long (i.e. no more than ~20 lines of code), if they are longer, they should be converted to named classes. Anonymous classes are common in java version less than 8. In java 8 there are Lambda expressions, which are similar to anonymous classes, but they are more compact.
In languages with support for first class functions listeners can be implemented like this:
def myFunction() { //code }
button.onClick(myFunction)
for simplicity some languages has the capability to define anonymous functions (aka lambdas):
button.onClick({ // code})
Are called "anonymous" because don't need a name to reference it, are used in place.
Java don't has first class functions, instead the listener pattern is implemented with a class that implement some interface:
class myListener implements ButtonListener {
public void listen(...);
}
button.onClick(myListener)
Analogous to the anonymous functions, for simplicity, java has the concept of anonymous classes, you can do:
button.onClick(new ButtonListener {
public void listen(..) { //code }
});
Note: this are simple "ilustrative" examples with an invented on the fly api :P
In java 8 first class functions (closures) are introduced, a huge and very good addition to java IMMO.
Inner classes: sometimes is good that one class is defined within the scope of another class, not the most useful java property IMMO, i use occasionally but can live without it in other languages.
I saw this Java snippet in the book Spring in Action, but I'm not familiar with the language construct.
new RowMapper() {
public Object mapRow() throws SQLException, DataAccessException {
Motorist motorist = new Motorist();
motorist.setId(rs.getInt(1));
motorist.setEmail(rs.getString(2));
motorist.setPassword(rs.getString(3));
motorist.setFirstName(rs.getString(4));
motorist.setLastName(rs.getString(5));
return motorist;
}
}
According the Spring documentation, RowMapper is an interface. It looks to me like an anonymous class definition based on the RowMapper interface. The new keyword is a little confusing, making me wonder if this also creates one instance of the anonymous class. I would guess yes, because if the class has no name, how will you ever create an instance after the line that defines it?
Can anyone confirm my guesses that:
this is an anonymous class definition based on the RowMapper interface, and
it creates a single instance of that class?
This is an anonymous class definition based on the RowMapper interface
That's precisely what it is.
It creates a single instance of that class?
Yep. That's correct.
That code is implementing the interface in an anonymous way.
The syntax would be similar to:
Runnable runnable = new Runnable() {
public void run() {
}
};
Note the semicolon at the end of the declaration. Here the runnable object, though holds the reference to the Runnable interface actually contains the implemented object. That's runtime polymorphism for you!
Your guesses are entirely correct. An anonymous class definition may be based on either a non-final class or on an interface, and you must implement all abstract (or interface) methods. The only available syntax for declaring anonymous classes is new, which also has the effect of instantiating exactly one instance of the anonymous class (in the course of the program, though, many instances of the same anonymous class could be created, if this code is executed several times).
Interface tells what methods the built class instance should have or if thy are label interfaces, then what kind of behavior to associate with it.
Anonymous classes are classes that basically while instantiating a class instance thy are also extending it with custom code. So if you are instantiating a interface, then you must write all the methods described with that interface, and as long as you do at least that much, then compiler will be happy. This is what is done here.
IS this is an anonymous class definition based on the RowMapper interface?
Yes. As you can see mapRow() function has been written. And if you debug the code you can see, that is not a class of an instance of interface, but class that extends interface. In case of abstract class or just class, it would be same - extended. So if class is final you cant write anonymous class for it.
Does it create a single instance of that class?
Well, it extends it and makes an instance of it. It will be single instance and any sequent call to it would result in a different class. If you debug the code, then you can even see different class names dynamically associated with it.
Solely from the code above and without knowing about RowMapper, all you can assume is that a new anonymous class based on RowMapper (which may be an interface or a class) is instantiated.
Declaring Anonymous class and in below example it creates two instances .
public class Multithread {
void test(){
new Runnable() {
#Override
public void run() {
System.out.println("1");
}
}.run();
new Runnable() {
#Override
public void run() {
System.out.println("11");
}
}.run();}
public static void main(String[] args) {
new Multithread().test();
}
}
Can someone explain this Java syntax to me?
What are those brackets doing inside the outer parentheses?
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
It's called an anonymous inner class. It creates an unnamed class that extends WindowAdapter (it would also have been possible to specify an interface, in which case the class would implement that interface), and creates one instance of that class. Inside the brackets, you must implement all abstract methods or all interface methods, and you can override methods too.
This is an anonymous inner class -- the brackets denote the beginning and ending of the class declaration. This is a potentially useful SO question, and a bunch of others.
And to complement andersoj's answer, you usually use them when a method expects an instance of X, but X is an abstract class or an interface.
Here, you're actually creating a derived class from WindowAdapter, and overriding one of the methods to do a specific task.
This syntax is very common for event handlers / listeners.
It is an anonymous inner class. It is just a shortcut. You can imagine how the code would look like if you needed to create it as a top level class:
class CloseApplicationWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
Then, inside your code you would do:
CloseApplicationWindowAdapter adapter = new CloseApplicationWindowAdapter();
addWindowListener(adapter);
Both solutions have exactly the same effect (althoug the anonymous class would create a Class$1.class file, for instance). Java programmers will often prefer the anonymous class approach if the anonymous class does not get too big/complicated/important.