Search code examples
javalocal-class

Java. local classes is there any reason not to make it 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!


Solution

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