The following code defines a class within a method.
final class OuterClass
{
private String outerString = "String in outer class.";
public void instantiate()
{
final String localString = "String in method."; // final is mandatory.
final class InnerClass
{
String innerString = localString;
public void show()
{
System.out.println("outerString : "+outerString);
System.out.println("localString : "+localString);
System.out.println("innerString : "+innerString);
}
}
InnerClass innerClass = new InnerClass();
innerClass.show();
}
}
Invoke the method instantiate()
.
new OuterClass().instantiate();
The following statement,
final String localString = "String in method.";
inside the instantiate()
method causes a compile-time error as follows, if the final
modifier is removed.
local variable localString is accessed from within inner class; needs to be declared final
Why does the local variable localString
need to be declared final
, in this case?
It's described very well in this article:
.. the methods in an anonymous class don't really have access to local variables and method parameters. Rather, when an object of the anonymous class is instantiated, copies of the final local variables and method parameters referred to by the object's methods are stored as instance variables in the object. The methods in the object of the anonymous class really access those hidden instance variables. Thus, the local variables and method parameters accessed by the methods of the local class must be declared final to prevent their values from changing after the object is instantiated.
Also refer to the JLS - 8.1.3. Inner Classes and Enclosing Instances for details and further explanation.
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