final 域为引用类型
public class FinalReference {/*** final 域.*/final int[] arr;static FinalReference ref;public FinalReference() {arr = new int[1];arr[0] = 1;}public static void writeOne() {ref = new FinalReference();}public static void writeTwo() {ref.arr[0] = 2;}public static void reader() {if (ref != null) {int temp = ref.arr[0];System.out.println("temp:" + temp);}}
}
对象引用“逸出”
public class ReferenceEscape {final int i;static ReferenceEscape escape;public ReferenceEscape() {i = 1; //1、写final 域.escape = this; //2、this引用再次“逸出”.}public static void writer() {new ReferenceEscape();}public static void reader() {if (escape != null) { //3int temp = escape.i; //4、final 域可能还未初始化.System.out.println("temp:" + temp);}}
}