接口中定義的字段自動具備 static 和 final 屬性,即編譯期常數(但可非常數表達式初始化)。
public interface RandVals {
int rint = (int)(Math.random() * 10);
long rlong = (long)(Math.random() * 10);
float rfloat = (float)(Math.random() * 10);
double rdouble = Math.random() * 10;
}
字段在類首次加載時初始化(首次訪問任意字段前),而非編譯期。每次運行程序值不同。
public class TestRandVals {
public static void main(String[] args) {
println(RandVals.rint); // 每次運行輸出不同
println(RandVals.rlong);
println(RandVals.rfloat);
println(RandVals.rdouble);
}
}
public static final,無需顯式聲明。