Вопрос

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!

Это было полезно?

Решение

People seem to be a bit confused about anonymous classes and local classes. This is a local class:

public void m() {
   class MyClass{}
   MyClass cl = new MyClass();
}

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:

public void m() {
   class MyClass{}
   MyClass cl = new MyClass();
   class MyOtherClass extends MyClass{}
   MyOtherClass cl2 = new MyOtherClass();
}

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.

Другие советы

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

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?"

"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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top