Author | Topic: Anonymous classes |
shan unregistered |
posted March 08, 2000 10:11 AM
Button b = new Button("ok"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ System.out.println("dsAS"); } }); What exactly is this doing???
|
Lucy C ranch hand |
posted March 08, 2000 10:38 AM
What exactly is this doing??? Ok - here's what's happening. You want to add an ActionListener to your button, so you need to call its addActionListener method, passing it an ActionListener object. Because you only need to use this object for this purpose, instead of creating a new class that extends ActionListener and instantiating it separately, you can create and instantiate it anonymously in one step when calling the button's addActionListener method. b.addActionListener(new ActionListener() { The "new ActionListener()" here instantiates an object of an anonymous class that extends Object and implements ActionListener. If you used the syntax "new SomeClass()", you'd get an instance of a class that extended SomeClass. public void actionPerformed(ActionEvent e){ This is where it gets even stranger, because after instantiating the class, you still have to define the class's members. The ActionListener interface has one method with this signature, so here you're just implementing the method. This is the method that's called on the anonymous object when the button is clicked. Finally, because this is all happening within your addActionListener method call, you need to finish the statement with a ";" as usual. Is that helpful? [This message has been edited by Lucy C (edited March 08, 2000).]
|
maha anna bartender |
posted March 08, 2000 10:45 AM
Functionally there is no difference between 1. defining a class which implements the listener interface and then registering an instance of this class as a eventListener for a component
2. defining an anononymous class,instantiate it,register it as eventListener to a component on the fly
My analysis: [This message has been edited by maha anna (edited March 08, 2000).]
|
| | |