Cannot refer to a non-final variable * inside an inner class defined in a different method"錯誤解析


    

  • 在使用Java局部內部類或者匿名內部類時,若該類調用了所在方法的局部變量,則該局部變量必須使用final關鍵字來修飾,否則將會出現編譯錯誤“Cannot refer to a non-final variable * inside an inner class defined in a different method” 下面通過一段代碼來演示和分析原因。

    [java]
    public class Example { 
     
        public static void main(String args[]) { 
            doSomething(); 
        } 
     
        private static void doSomething() { 
            final String str1 = "Hello"; 
            // String str2 = "World!";  
            // 創建一個方法裏的局部內部類  
            class Test { 
                public void out() { 
                    System.out.println(str1); 
                    // System.out.println(str2);  
                } 
            } 
            Test test = new Test(); 
            test.out(); 
     
        } 
     

    public class Example {

     public static void main(String args[]) {
      doSomething();
     }

     private static void doSomething() {
      final String str1 = "Hello";
      // String str2 = "World!";
      // 創建一個方法裏的局部內部類
      class Test {
       public void out() {
        System.out.println(str1);
        // System.out.println(str2);
       }
      }
      Test test = new Test();
      test.out();

     }

    }       上面代碼若去掉第9行和第14行的註釋符號,則第14行就會給出“Cannot refer to a non-final variable * inside an inner class defined in a different method”這樣的編譯錯誤。原因如下:在方法中定義的變量時局部變量,當方法返回時,局部變量(str1,str2)對應的棧就被回收了,當方法內部類去訪問局部變量時就會發生錯誤。當在變量前加上final時,變量就不在是真的變量了,成了常量,這樣在編譯器進行編譯時(即編譯階段)就會用變量的值來代替變量,這樣就不會出現變量清除後,再訪問變量的錯誤。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章