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!
A local class is visible only within the block that defines it; it can never be used outside that block. Local classes cannot be declared public, protected, private, or static. These modifiers are for members of classes; they are not allowed with local variable declarations or local class declarations.
In addition, a local class has access to local variables. However, a local class can only access local variables that are declared final. When a local class accesses a local variable or parameter of the enclosing block, it captures that variable or parameter.
In Java a static nested class is essentially a normal class that has just been nested inside another class. Being static, a static nested class can only access instance variables of the enclosing class via a reference to an instance of the enclosing class.
A class declared inside a function becomes local to that function and is called Local Class in C++. A local class name can only be used locally i.e., inside the function and not outside it. The methods of a local class must be defined inside it only. A local class can have static functions but, not static data members.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With