What is this in java? Attaching methods "on the fly"?
I saw something like this today:
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
What does the following part mean?
new AClass(){ this part }
Can I "extends" and create a new instance of this class inli开发者_JAVA技巧ne?
I have tried to google it, but I didnt know how what it was called =/
PS: learning java =p
It's called an "anonymous class"... it's a shorthand way of implementing an interface, or extending an existing class (usually an abstract "Adapter" or "Helper" class), without bothering to name it.
You see it commonly in Swing code... implementing window and mouse listeners.
This looks (at face value) like a decent discussion of the topic: http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html
Cheers. Keith.
To add to Bohemian's answer, it's the same as doing something like this
class MyWindowAdapter extends WindowAdapter() {
@Overide
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
and
frame.addWindowListener(new MyWindowAdapter());
It is just an anonymous inner class, it is useful when you are only going to use that interface implementation only once, it can be very useful as otherwise you would have to create an entire class just for that.
It's called an anonymous class.
精彩评论