一、illegal forward refrence
前天寫一個(gè)類時(shí)遇到一個(gè)很眼生的編譯錯(cuò)誤(問題簡化后):
1
punlic final class Constants
{
2
public static int VAR2 = VAR1 + 1;
3
public static int VAR1 = 1;
4
}



2

3

4

編譯時(shí)出錯(cuò)(第2行):
illegal forward refrence
仔細(xì)一想,是因?yàn)閂AR2引用的VAR1在VAR2之后定義,看來在Java中定義static變量時(shí)應(yīng)遵循“聲明先于使用”的原則。
二、static塊
還是上一個(gè)類,VAR1和VAR2定義成final,值存在一個(gè)properties文件中,在使用前必須將值load進(jìn)來:
System.getProperties().load(new FileInputStream("constants.properties"));
于是將上面的代碼放在static塊中:















但在運(yùn)行時(shí)VAR1和VAR2沒有被賦值,debug后發(fā)現(xiàn)static塊根本沒有執(zhí)行。于是頓悟:final變量在編譯時(shí)便被編譯器計(jì)算、賦值,因此在運(yùn)行時(shí)沒有必要執(zhí)行static塊。