这在java中是什么? “即时”附加方法?

发布于 2024-11-18 08:40:16 字数 344 浏览 3 评论 0原文

今天看到这样一句话:

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

神爱温柔 2024-11-25 08:40:16

它被称为“匿名类”......它是实现接口或扩展现有类(通常是抽象“适配器”或“帮助器”类)的一种简写方式,而无需命名它。

您通常会在 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.

薆情海 2024-11-25 08:40:16

要添加波西米亚人的答案,这与做这样的事情是一样

class MyWindowAdapter extends WindowAdapter() {

        @Overide 
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
}

frame.addWindowListener(new MyWindowAdapter());

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());
橘香 2024-11-25 08:40:16

它只是一个匿名内部类,当您只使用该接口实现一次时,它非常有用,否则您将不得不为此创建一个整个类。

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.

你げ笑在眉眼 2024-11-25 08:40:16

它称为匿名类。

It's called an anonymous class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文