Method local inner class in Java is limited to a code section, and it can be processed only inside the same code section it is declared in. Hence it can never execute modifiers. A local inner class instance can be delivered as argument and retrieved from methods, and is available inside a valid scope.
Purpose of Method Local Inner class
The only limitation in method local inner class is that a local parameter can be executed only when it is defined ‘final’. The basis for this limitation associates primarily to multi-threading problems and makes sure that every variable has definite values when accessed from local inner class. The method executing the local parameters can be called after the execution of the method, within which the local inner class was declared. As a result, the local parameters will no longer retain their values. Hence the values must be fixed before creating the local inner class object. If required, a non-final variable can be copied into a final variable which is subsequently executed by the local inner class.
The following example program will not compile unless the statement System.out.println(b); is eliminated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class J2EEReferenceOuterClass { private int a = 5; public void exampleMethod() { int b = 10; // here the variable is not declared final final int c = 20; class J2EEReferenceLocalInnerClass { public void accessSampleOuter() { System.out.println(a); System.out.println(b); // (Error: Cannot refer to non-final // variable b inside an inner class // defined in a different method) System.out.println(c); } } J2EEReferenceLocalInnerClass innercls = new J2EEReferenceLocalInnerClass(); innercls.accessSampleOuter(); } } |
1 2 3 4 5 6 |
public class LocalInnerTest { public static void main(String[] args) { J2EEReferenceOuterClass outercls = new J2EEReferenceOuterClass(); outercls.exampleMethod(); } } |
OUTPUT
Compilation Error
On declaring the variable ‘b’ as final, the output for the program would be
5
10
20
On eliminating the statement ‘System.out.println(b);’ the output would be,
5
20
It is obvious that a method local inner class can never be addressed (i) public, (ii) private, (iii) protected, (iv) static or (v) transient as it is local to a method. Either abstract or final can be applied as modifiers to a method local inner class.
Leave a Reply