Java中如何使用匿名内部类? [英] How are Anonymous inner classes used in Java?

查看:548
本文介绍了Java中如何使用匿名内部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中匿名类的用途是什么?我们可以说使用匿名类是Java的优势之一吗?

What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?

推荐答案

通过匿名类",我认为您的意思是

By an "anonymous class", I take it you mean anonymous inner class.

当使用某些扩展名"(例如,覆盖方法)创建对象的实例时,匿名内部类会变得很有用,而不必实际子类化.

An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.

我倾向于将它用作附加事件侦听器的快捷方式:

I tend to use it as a shortcut for attaching an event listener:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // do something
    }
});

使用此方法可以使编码更快一些,因为我不需要创建实现ActionListener的额外类-我可以实例化一个匿名内部类而无需实际创建单独的类.

Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener -- I can just instantiate an anonymous inner class without actually making a separate class.

我只将这种技术用于快速而肮脏的"任务,而使整个课堂变得不必要.具有多个功能完全相同的匿名内部类应重构为实际类,无论是内部类还是单独的类.

I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.

这篇关于Java中如何使用匿名内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆