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

查看:36
本文介绍了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天全站免登陆