Java 構造函數
]
在Java中為靜態最終變量賦值
在Java中,可以在構造函數或聲明中為非靜態最終變量賦值。但是,靜態最終變量不能在構造函數中賦值; 必須為他們的聲明賦予一個值。
例如,以下程序正常工作。
class Test {
final int i; // i could be assigned a value here or constructor or init block also.
Tets() {
i = 10;
}
//other stuff in the class
}
如果我們將i定義為靜態最終結果,那么我們必須將這個值分配給i。
class Test {
static final int i; // Since i is static final, it must be assigned value here or inside static block .
static{
i=10;
}
//other stuff in the class
}
這種行為很明顯,因為靜態變量是在一個類的所有對象之間共享的; 如果靜態變量是最終的,那么創建一個新對象會改變不允許的靜態變量。
Java 構造函數