Cannot refer to a non-final variable inside an inner class defined in a different method

前端 未结 20 2273
一向
一向 2020-11-21 05:04

Edited: I need to change the values of several variables as they run several times thorugh a timer. I need to keep updating the values with every iteration through the timer

相关标签:
20条回答
  • 2020-11-21 05:50

    Just an another explanation. Consider this example below

    public class Outer{
         public static void main(String[] args){
             Outer o = new Outer();
             o.m1();        
             o=null;
         }
         public void m1(){
             //int x = 10;
             class Inner{
                 Thread t = new Thread(new Runnable(){
                     public void run(){
                         for(int i=0;i<10;i++){
                             try{
                                 Thread.sleep(2000);                            
                             }catch(InterruptedException e){
                                 //handle InterruptedException e
                             }
                             System.out.println("Thread t running");                             
                         }
                     }
                 });
             }
             new Inner().t.start();
             System.out.println("m1 Completes");
        }
    }
    

    Here Output will be

    m1 Completes

    Thread t running

    Thread t running

    Thread t running

    ................

    Now method m1() completes and we assign reference variable o to null , Now Outer Class Object is eligible for GC but Inner Class Object is still exist who has (Has-A) relationship with Thread object which is running. Without existing Outer class object there is no chance of existing m1() method and without existing m1() method there is no chance of existing its local variable but if Inner Class Object uses the local variable of m1() method then everything is self explanatory.

    To solve this we have to create a copy of local variable and then have to copy then into the heap with Inner class object, what java does for only final variable because they are not actually variable they are like constants(Everything happens at compile time only not at runtime).

    0 讨论(0)
  • 2020-11-21 05:51

    If the variable required to be final, cannot be then you can assign the value of the variable to another variable and make THAT final so you can use it instead.

    0 讨论(0)
提交回复
热议问题