In Java 8, this has changed a little bit. You can now access variables that are effectively final. Relevant snippet and example from the Oracle documentation (emphasis mine):
However, starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.
Effectively final: A non-final variable or parameter whose value is never changed after it is initialized is effectively final.
For example, suppose suppose that the variable
numberLengthis not declared final, and you add the highlighted assignment statement in thePhoneNumberconstructor:PhoneNumber(String phoneNumber) { numberLength = 7; // From Kobit: this would be the highlighted line String currentNumber = phoneNumber.replaceAll( regularExpression, ""); if (currentNumber.length() == numberLength) formattedPhoneNumber = currentNumber; else formattedPhoneNumber = null; }Because of this assignment statement, the variable
numberLengthis not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from an inner class must be final or effectively final" where the inner classPhoneNumbertries to access thenumberLengthvariable:if (currentNumber.length() == numberLength)Starting in Java SE 8, if you declare the local class in a method, it can access the method's parameters. For example, you can define the following method in the PhoneNumber local class:
public void printOriginalNumbers() { System.out.println("Original numbers are " + phoneNumber1 + " and " + phoneNumber2); }The method
printOriginalNumbersaccesses the parametersphoneNumber1andphoneNumber2of the methodvalidatePhoneNumber