方法中內部類訪問方法的局部變量,該變量必須要用final修飾


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

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時,變量就不在是真的變量了,成了常量,這樣在編譯器進行編譯時(即編譯階段)就會用變量的值來代替變量,這樣就不會出現變量清除后,再訪問變量的錯誤。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM