Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Final passed as parameter [duplicate]

In the following example it works and compile by setting the parameter int i as final

class Miner1
{
    Miner getMiner(final int i) {
        return new Miner() {                
           public void perform_work() { 
              System.out.println(i);
           }
        };
    }

interface Miner { void perform_work(); }

Otherwise if not set to final as the preceding example it won't compile. Does anybody know why? It should be on scope even without final as the curly parenthesis are not yet closed.

Thanks in advance.

like image 660
Rollerball Avatar asked Jul 24 '26 21:07

Rollerball


2 Answers

This is not to do with scope it is do with the anonymous inner classes.

You cannot access a local variable from an anonymous class that is declared in the parent class unless that variable is final.

Take a look at this other question on SO that explains the logic.

like image 154
Boris the Spider Avatar answered Jul 26 '26 10:07

Boris the Spider


It doesn't have anything to do with scope.

In Java, an anonymous class can only refer to those variables from outside scopes that are final.

From the JLS:

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.

like image 39
NPE Avatar answered Jul 26 '26 10:07

NPE