Effectively final variables in Java
TIL what effectively final variables in Java are.
A variable or parameter whose value is never changed after it is initialised is effectively final.
—The Java™ Tutorials: Local Classes
Example
Suppose that the variable postcodeLength
is not declared final, and you add the assignment statement in the Postcode
constructor to change the length of a valid postcode to 7 characters:
Postcode(String postalCode) {
postcodeLength = 7;
String currentPostalCode = postalCode.replaceAll(
regularExpression, "");
if (currentPostcode.length() == postcodeLength) {
formatterPostcode = currentPostalCode;
} else {
formattedPostcode = null;
}
}
Because of this assignment statement, the variable postcodeLength
is 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 class PostCode
tries to access the postcodeLength
variable:
if (currentPostcode.length() == postcodeLength)