Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does book say final is needed here?

Tags:

java

class

final

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");
    }
} ///:~
like image 565
DeadNerd Avatar asked Dec 18 '22 14:12

DeadNerd


1 Answers

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.

like image 149
ernest_k Avatar answered Jan 01 '23 18:01

ernest_k