简体   繁体   中英

Non final variable from inner class : should be automatically fixed by compiler?

When I use a non final variable from an inner class, I have a compile error :

public static void main(String[] args) {
    String s = "hello";
    s += "world";
    Object myObj = new Object() {
        public String toString() {
            return s; // compile error
        }
    };
    System.out.println(myObj);
}

However, I can fix this by adding a dummy final variable tmp that references the other variable I would like to access :

public static void main(String[] args) {
    String s = "hello";
    s += "world";
    final String tmp = s;
    Object myObj = new Object() {
        public String toString() {
            return tmp; // that works!
        }
    };
    System.out.println(myObj);
}

This process of adding a temporary final variable could be easily automatized, by a compiler for example.

My question is : why does the compiler do not perform automatically that simple change that allows us to get rid of this error ?

Compiler can't replace all references to local variable with a constant but when the instance of inner class is constructed, the value is passed to appropriate constructor and stored in variable. According to need, It is cumbersome to automatically implement it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM