Java8中內部類不再需要明確定義外部類變數為final
阿新 • • 發佈:2019-02-16
public class OutClass { public void outFunc() { // java8以前的寫法 // final String outFuncVar = "outFuncVar"; // java8以後可以這樣寫 String outFuncVar = "outFuncVar"; @SuppressWarnings("unused") class NestClass { public void NestFunc() { // 開啟後報錯 // Local variable outFuncVar defined in an enclosing scope must be final or effectively final // outFuncVar = "重新賦值"; System.out.println(outFuncVar); } } } // 特例 public static void outFunc2() { final int k = 1; // 下面這種寫法依然報錯 // int k = 1; @SuppressWarnings("unused") class LocalClass { public void LocalFunc() { int m = 1; switch (m) { case k: break; } } } } }
1、Java8引入一個effectively final的概念,當內部類訪問外部類變數時,只要內部類不對外部變數重新賦值,那麼外部類變數就是一個事實上的final變數,Java會隱含地將外部變數宣告為final。
2、However, starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.
effectively final有一個特殊例子,參考上面的outFunc2
參考