3 回答

TA貢獻1810條經(jīng)驗 獲得超4個贊
我的問題是類級別 i 的靜態(tài)值,即 15 應(yīng)該打印,因為靜態(tài)值不應(yīng)更改。
當(dāng)變量是靜態(tài)的時,同一類的所有對象中僅存在該變量的一個實例。因此,當(dāng)您調(diào)用 時obj1.i = 25,您將更改類的所有i實例,包括您當(dāng)前所在的實例。
如果我們單步執(zhí)行代碼并看看它在做什么,這可能會更清楚:
public static void main(String[] args) {
ParentClass obj1= new ParentClass();
// Set i for ALL ParentClass instances to 10
obj1.i=10;
// See below. When you come back from this method, ParentClass.i will be 25
obj1.printvalue();
// Print the value of i that was set in printValue(), which is 25
System.out.println("The value of i is " +i); /
}
public void printvalue() {
ParentClass obj1= new ParentClass();
// Create a new local variable that shadows ParentClass.i
// For the rest of this method, i refers to this variable, and not ParentClass.i
int i =30;
// Set i for ALL ParentClass instances to 25 (not the i you created above)
obj1.i=25;
// Print the local i that you set to 30, and not the static i on ParentClass
System.out.println("The value of i in the method is " +i);
}

TA貢獻1820條經(jīng)驗 獲得超10個贊
int i
是一個局部變量,僅存在于 的范圍內(nèi)printvalue()
(此方法應(yīng)命名為printValue()
)。您將局部變量初始化i
為 30。
obj1.i=25
是Object 中的靜態(tài) 字段。當(dāng)您實例化 時,您將創(chuàng)建一個靜態(tài)字段值為 10 的實例。然后將 的值更改為 25。i
obj1
obj
ParentClass obj1= new ParentClass();
ParentClass
i
obj1.i
這與局部變量無關(guān)int i
。

TA貢獻1895條經(jīng)驗 獲得超3個贊
您有不同的變量(在不同的范圍內(nèi)),它們都被稱為i
:
原始整數(shù)類型的靜態(tài)變量:
static int i=15;
原始整數(shù)類型的局部變量(僅在其所屬方法的范圍內(nèi)可見
printvalue()
:int i =30;
您可以從非靜態(tài)上下文訪問靜態(tài)變量,但不能從靜態(tài)上下文訪問實例變量。
在您的printvalue()
方法中,您將 local var 設(shè)置i
為值 30,然后為 static variable 設(shè)置一個新值 (25)?i
。因為兩者共享相同的變量名,所以靜態(tài)變量i
被它的本地對應(yīng)變量“遮蔽”......這就是輸出為 30 而不是 25 的原因。
添加回答
舉報