In java, why should private variables be declared final?

final Object o;

List l = new ArrayList(){{
    // closure over o, in lexical scope
    this.add(o);
}};

why oshould be declared final? Why don't other variable-var JVM languages ​​have this requirement?

+3
source share
2 answers

This is not JVM-deep; it all happens at the syntax-sugar level. The reason is that exporting unconfigured var through closure makes it vulnerable to datarace problems, and since Java was designed as a “blue-collar” language, such an amazing change in the behavior of the otherwise manual and safe local var was considered too “advanced”.

+3
source

, final.

Java, , . , , (, ..), , . , "" , . , Python, Ruby, JavaScript, , - . JVM, , .

, , ( , , ). , , . , :

Object o;

Object x = new Object(){
    public String toString() {
        return o.toString();
    }
};
o = somethingElse;
System.out.println(x.toString()); // prints the original object, not the re-assigned one
                                  // even though "o" now refers to the re-assigned one

o, , . , , o, o , ; . , .

, , , -; final.

, , final final. final - final.

Object a; // non-final
final Object o = a;

Object x = new Object(){
    Object m = o; // non-final
    public String toString() {
        return ,.toString();
    }
};

, , , .

+1

All Articles