这在java中是什么? “即时”附加方法?
今天看到这样一句话:
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
下面这句话是什么意思?
new AClass(){ this part }
我可以“扩展”并内联创建此类的新实例吗?
我试过用谷歌搜索它,但我不知道它叫什么=/
PS:学习java =p
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 inline?
I have tried to google it, but I didnt know how what it was called =/
PS: learning java =p
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它被称为“匿名类”......它是实现接口或扩展现有类(通常是抽象“适配器”或“帮助器”类)的一种简写方式,而无需命名它。
您通常会在 Swing 代码中看到它...实现窗口和鼠标侦听器。
这看起来(从表面上看)像是对该主题的一个不错的讨论: http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html
干杯。基思.
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
and
它只是一个匿名内部类,当您只使用该接口实现一次时,它非常有用,否则您将不得不为此创建一个整个类。
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.