Method in constructor?
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
They are called anonymous classes, you can read up on them at http://download.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
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)
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());
Its called anonymous Inner class, where object is declared and initialized at the same time.
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.
精彩评论