從我的理解,你想知道爲什麼代碼是有效的在下列情況下,當你期望它會引發錯誤。
在這種情況下,你是不是改變場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教程,仔細查看代碼和變量名稱。
你是什麼意思「的意思,但這並不具有成爲」?它打印出常數的值,即18。爲什麼你會期望別的嗎?真的不清楚哪一方面讓你感到困惑,以及你期望發生什麼。 –