简体   繁体   中英

Java Scope and Lifetime (inner classes)

I need to explain why the following code would fail to compile (in terms of scope and lifetime):

class ClassInMethod
{
   public static void main(String[] args)
   {
      int local = 1;

      class Inner
      {
         public void method()
         {
             System.out.println(local);
         }
      }
   }
}

I think it's because: Any local variable used but not declared in an inner class must be declared 'final'. Thus, in this example 'local' must be declared final because its scope and lifetime end within the main method (so needs to be changed to: final int local = 1;).

Any other suggestions?

请参阅http://techtracer.com/2008/04/14/mystery-of-accessibility-in-local-inner-classes/了解有关编译器如何使用final技巧来解决内部类问题的说明(例如,作用域和一生的问题)。

Just try to compile it. The compiler outputs:

ClassInMethod.java:11: local variable local is accessed from within inner class; needs to be declared final
    System.out.println(local);
                       ^
1 error

The reason why you have to make the local variables final is that Java copies their values into the instance of the inner class. What happens behind the scenes is that the compiler generates bytecode that (roughly) corresponds to this:

class ClassInMethod {
    public static void main(String[] args) {
        int local = 1;

        // this happens when you do: new Inner()
        ClassInMethod_main_Inner inner = new ClassInMethod_main_Inner();
        inner.local = local;
    }
}

// the inner class
class ClassInMethod_main_Inner {
    int local;

    public void method() {
        System.out.println(local);
    }
}

If local weren't final , and you could change its value between when Inner is instantiated, and when method() is called, the call to method() would use the old value of local . This would likely be incorrect behaviour. The reason final is mandated is to make the behaviour of inner classes more intuitive.

(There are languages that don't have this restriction, but it requires explicit support from the compiler and runtime. Java's developers have so far not decided to dedicate their effort to implementing 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