爪哇。本地课程有什么理由不最终确定吗?
我有一个关于 Java 中的本地类(在方法中或以 { } 为界的块中声明的类)的问题。
有什么理由不将本地类声明为final?我们不能从本地类继承其他类(如果它没有在同一范围内定义),但是当我们将其声明为final时,也许编译器可以使代码变得更简单?
谢谢你!
I have a question about local classes in Java (classes that declares in the method or in blocks bounded by { }).
Is there any reason not to declare local class as final? We cannot inherit other class from local class (if it's not defined at the same scope), but when we declare it as final, maybe compiler can make code much simpler?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
人们似乎对匿名类和本地类有点困惑。这是一个本地类:
您可以将
MyClass
声明为final,但实际上可以从它继承,因此Java中的其他任何地方都可以将其声明为final以避免这种情况:据我所知,匿名类不被认为是最终的。然而,从语法上讲,无法从它们继承,因此需要强大的类文件 hack 才能做到这一点。
People seem to be a bit confused about anonymous classes and local classes. This is a local class:
You can declare
MyClass
final, but it is actually possible to inherit from it, so as anywhere else in Java can declare it final to avoid this:To my knowledge, anonymous classes are not considered final. However, syntactically there is no way to inherit from them, so it would require a mighty class file hack to do so.
在任何情况下都没有理由不声明final,除非您明确以继承为目标。
我想不这样做的原因主要是疏忽,因为在大多数情况下没有明显的实际后果。一些代码分析工具,如 FindBugs 会警告您某个字段是否可以声明为最终字段。
关于普遍使用
final
关键字的问题可以找到很好的答案 这里There is no reason not to declare final in any case, except when you explicitly aim for inheritance.
I guess the reason for not doing so is mostly negligence as there are no noticeable practical consequences in most cases. Some code analysis tool like FindBugs warn you if a field could be declared final.
A question about the universal use of the
final
keyword with very good answers may be found here没有理由不这样做,除非它是代码中不需要的关键字。 IE。没有理由不这样做,也没有理由这样做。如果该类是在方法中声明的,则无法从任何其他位置访问该类,因此无法对其进行子类化。那么为什么要阻止一些无法完成的事情呢?
因此添加这个词不会以任何方式改变行为,但会让你的代码变得混乱。有人可能会想“为什么这门课是期末考试,我是不是错过了什么奇特的东西?”
There is not a reason not to except that it is an unneeded keyword in your code. ie. there is no reason not to, and no reason to do so. If the class is declared within a method than it cannot be accessed from any other place and therefore cannot be subclassed. So why prevent something that cannot be done?
So adding the word does not change behavior in any way but does clutter your code. Someone might think "why is this class final, am I missing something fancy?"
“在方法中声明的类”是匿名类,“在以 { } 为界的块中声明的类”是内部类。
匿名类不能声明为
final
,因为无法继承它。内部类可以是
final
,除非它有任何子类。"classes that declares in the method" are anonymous classes, and "classes that declares in blocks bounded by { }" are inner classes.
Anonymous classes cannot be declared as
final
because there is no way to inherit it.Inner classes can be
final
unless there would be any subclasses of it.