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