方法本地内部类在Java中提供了什么好处? [英] What benefit do method-local inner classes provide in Java?

查看:136
本文介绍了方法本地内部类在Java中提供了什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了 SCJP书籍,我真的很难想到它们的任何实际用途。

I've just read through the chapter on method-local inner classes in the SCJP book, and I'm really struggling to think of any practical use for them.

我一直都有这样的印象:方法应该尽可能小而且特定于他们的任务( Orthogonality IIRC),因此即使是最简单的内部类也会产生重要且笨拙的方法。

I've always been under the impression, that methods should be as small and specific to their task as possible (Orthogonality IIRC), so introducing even the simplest inner class would create heft and unwieldy methods.

任何人都可以提出建议方法本地内部类的良好实际用法?到目前为止,感觉好像我可能必须完全理解它们才能通过考试,而不是用于日常编码。

Can anyone suggest a good practical usage for method local inner classes? So far it feels as if I might have to understand them purely for passing the exam, and not for use in everyday coding.

干杯

推荐答案

在大多数情况下(例如对于动作侦听器,runnable等),您将使用匿名类而不是方法本地命名类。

In most cases (e.g. for action listeners, runnables and such) you would use anonymous classes instead of method-local named classes.

但是有一个命名类可以做,匿名类不能:实现多个接口,或扩展类和接口。此外,您可以创建此类的多个对象(不使用循环)。

But there is one thing which named classes can do and anonymous classes can't: implementing more than one interface, or extending a class and interfaces, too. Also, you can create more than one object of this class (without using a loop).

这篇关于方法本地内部类在Java中提供了什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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