That code is from the book Thinking in Java. I don't know why I must add the final
syntax here. I deleted the final
and the program still compiled. However, the book says I must add it.
// initialization. A briefer version of Parcel5.java.
public class Parcel9 {
// Argument must be final to use inside
// anonymous inner class:
public Destination destination(final String dest) {
return new Destination() {
private String label = dest;
public String readLabel() { return label; }
};
}
public static void main(String[] args) {
Parcel9 p = new Parcel9();
Destination d = p.destination("Tasmania");
}
} ///:~
It's very likely that the book (or chapter/section) was written before the Java 8 age.
Java imposes a limitation on anonymous classes, which may not access a local variable unless it's final.
In Java 8, that limitation is applicable to lambda expressions too. But, in addition to that, Java 8 added the notion of effectively final, which makes the compiler smarter by making it detect that the variable is final by virtue of it not being reassigned locally, thereby making the explicit use of the final
keyword optional in such cases.
So, if you compile that code on Java 7 or older, you'll get the compiler error that the book is teaching its readers to avoid.
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