2017-07-29 86 views
-4

我試圖編譯這段代碼靜態和最終

public class Foo { 
    static final int x = 18; 

    public void go(final int y){ 
     System.out.println(x); 
    } 
} 

public class Mixed2 { 
    public static void main(String[] args){ 

     Foo f = new Foo(); 
     f.go(11); 
    } 
} 

而且它編譯。甚至給出了結果(18) 但是,這不一定是。這是爲什麼發生? 我使用的想法 謝謝

+3

你是什麼意思「的意思,但這並不具有成爲」?它打印出常數的值,即18。爲什麼你會期望別的嗎?真的不清楚哪一方面讓你感到困惑,以及你期望發生什麼。 –

回答

0

從我的理解,你想知道爲什麼代碼是有效的在下列情況下,當你期望它會引發錯誤。

在這種情況下,你是不是改變場x,而是簡單地增加一個新的變量名稱相同,即覆蓋(陰影)領域x

public class Foo { 
    static final int x = 18; // field x 

    // This creates a new variable x which hides the field x above 
    public void go(final int x /* variable x */) { 
     System.out.println(x); 
    } 
} 

在今後的2箱子,你正在試圖改變x,這將導致一個錯誤:

public class Foo { 
    static final int x = 18; // field x 

    // The field x is final and cannot be changed. 
    public void go() { 
     x += 1; 
    } 
} 

public class Foo { 
    static final int x = 18; // field x 

    // The variable x is final and cannot be changed. 
    public void go(final int x /* variable x */) { 
     x += 1; 
    } 
} 

舊答:如果您正在嘗試打印11,則應撥打System.out.println(y)而不是使用x

請嘗試遵循一些Java教程,仔細查看代碼和變量名稱。

+0

我不試試編譯這個。相反,我認爲它不應該被編譯。但是代碼「public void go(final int x){...}」也是編譯的。但是,這是一個嘗試改變常數,並應該引起異常。不是嗎? –

+0

@YeroSun當你爲函數的'final int x'指定一個參數時,它會引入一個隱藏字段static final int x(它是_shadows_ it)的新變量。如果你想要出現錯誤,你需要嘗試在'go'裏面指定'x',但是創建任何其他的變量'x'而不是已經存在的字段。 –

0

事實是,您不能更改最終的值 ...但是,您不會更改任何最終數字,如果是的話,您將得到編譯器錯誤,而不是例外。

  • 靜態使得變量之間的所有相同的類 - 更改go()靜態仍然可以讓你訪問它,但是做go()靜態和刪除:

    知道靜態和最終之間的差異是很重要的從x靜電會阻止您引用x,因爲go()功能不知道哪個Foo類中找到x

  • 最終使一個變量unchangeable-我不知道任何性能方面的原因在t他的,但主要是常數。
    • 例如,你不希望能夠爲Boolean.TRUE的值設置爲false

public class Foo { 
    static final int x = 18; 

    public void go(final int y) { 

     // This is not possible because 'x' is final, 
     // however the state of 'y' does not matter, 
     // because its value is not being changed 
     x = y; 
     System.out.println(x); 
    } 
} 

public class Mixed2 { 
    public static void main(String[] args){ 

     Foo f = new Foo(); 
     f.go(11); 
    } 
}