I was practicing the Inner Class concept and inside that, Method Local Inner Class.
I know the usage of final keyword very well but in this program, I am not able to understand its significance:
//method local inner class example
package practice;
public class OuterClass
{
void my_Method()
{
final int n=23; //why final is required?
class MethodInner_Demo
{
public void print()
{
System.out.println("This is method local inner class: "+n);
}
}
MethodInner_Demo inner=new MethodInner_Demo();
inner.print();
}
public static void main(String[] args)
{
OuterClass outer=new OuterClass();
outer.my_Method();
}
}
And without using final, it is throwing an error in this part,
System.out.println("This is method local inner class: "+n);
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot refer to the non-final local variable n defined in an enclosing scope
Please explain!
Thank you.