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

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