![](/img/trans.png)
[英]Why my program doesn't show compile time error when final class variable is not initialized?
[英]Compile time error “final variable is not initialized”
我遇到一個問題,在嘗試一些代碼片段時遇到了一個代碼
class O
{
final int i;
O()
{
i=10;
}
O(int j)// error here as THE BLANK FINAL FIELD i IS NOT INITIALIZED
{
j=20;
System.out.println(j);
}
}
class Manager3
{
public static void main(final String[] args)
{
O n1=new O();
//O n2=new O(10);
//n1.i=20;
//System.out.println(j1.i);
}
}
但是如果我用參數注釋構造函數,我不會得到任何錯誤。
我的問題是,當我將構造函數都放入代碼中時,為什么會出現此編譯時錯誤?為什么刪除參數化構造函數時卻沒有出現任何錯誤?
我知道我們必須初始化我的最終變量,但是我正在構造函數中對其進行初始化,因此如果我編寫此代碼:-
class O
{
final int i;
O()
{
i=10;
}
}
class Manager3
{
public static void main(final String[] args)
{
O n1=new O();
}
}
每一個都工作正常,代碼正在編譯。
我的問題是,如果我引入另一個構造函數,會出現什么問題。 即使錯誤發生在我寫參數化缺點的那一行。
我對JAVA有所了解,但是我對這段代碼感到困惑。
final int i;
您已將i
定義為final
。 您只能在構造函數中將值分配給最終變量。
O(int j)// error here as THE BLANK FINAL FIELD i IS NOT INITIALIZED
{
j=20;
System.out.println(j);
}
在這里,您沒有為i
賦值。 如果有人使用此構造函數(帶參數的構造函數)創建對象,則不會分配i
值。
如何解決呢?
如您所說,您必須注釋該構造函數(或)像在其他構造函數中一樣在此構造函數中分配i
值。
O(int j){
this(); // <----- you can add this line.
j=20;
System.out.println(j);
}
final
變量必須在聲明時初始化,或分配給構造函數主體中的值。 如果不初始化final
變量,則會出現編譯器錯誤。
如果調用第二個構造函數,則變量永遠不會賦值。
“ i”是實例最終變量,因此我們需要在我定義的每個構造函數中對其進行初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.