Reputation: 23206
I have often come across this snippet :
General form of invokeLater is - static void invokeLater(Runnable obj)
But i have often come across these types of codes:
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new tester();
}
});
}
or-----(example of another type)
{
clean.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
cleanActionPerformed(ae);
}
});
}
Now what is this? There is method in the constructor!! I am unable to understand the way of writing these snippets. Explain very clearly
Upvotes: 2
Views: 144
Reputation: 47183
What you see are anonymous inner classes. They are one-shot classes that you won't use anywhere else.
Take a look at this piece:
clean.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
cleanActionPerformed(ae);
}
});
addActionListener
is expecting an implementation of an ActionListener, which is an interface.
Now, you could write a whole new class that implements it and then put an instance of it as an argument of addActionListener
, but this way is faster to write (and a bit harder to read) if you won't use such a class anywhere else.
The same effect could have been achieved with this:
class SomeActionListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
cleanActionPerformed(ae);
}
}
...
clean.addActionListener(new SomeActionListener());
Upvotes: 1
Reputation: 73484
These are just anonymous classes or a local class without a name. Anonymous classes are usually used when you will only reference a class once.
Instead of doing addListener(this)
and having your class implement some interface.
Upvotes: 0
Reputation: 5612
Its called anonymous Inner class, where object is declared and initialized at the same time.
Upvotes: 0
Reputation: 9382
They are called anonymous classes, you can read up on them at http://download.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
Upvotes: 3
Reputation: 76898
They're anonymous classes.
You could write them as a class in their own file,instantiate it, and pass it as the argument... but for one-off use that is the easier way to do it.
(As Matt notes in a comment below, "easier" in that you don't have to create the files and write out the classes, etc)
Upvotes: 2