亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 Main 方法中的靜態變量值會發生變化?

為什么 Main 方法中的靜態變量值會發生變化?

慕沐林林 2024-01-05 15:23:36
我寫了一個簡單的程序,如下所示,這讓我感到困惑:    package BasePackage;public class ParentClass {    static int i=15;    double f=4.5;       public static void main(String[] args) {        ParentClass obj1= new ParentClass();        obj1.i=10;        obj1.printvalue();        System.out.println("The value of i is " +i);    }    public void printvalue()    {        ParentClass obj1= new ParentClass();        int i =30;        obj1.i=25;        System.out.println("The value of i in the method is " +i);    }}我得到的輸出類似于 The value of i in the method is 30 and the value of i is 25. 我的問題是類級別 i 的靜態值,即 15 應該被打印,因為靜態值不應更改。另外,我在方法中更改了 i =25 的值,那么為什么沒有打印它而不是 30?
查看完整描述

3 回答

?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

我的問題是類級別 i 的靜態值,即 15 應該打印,因為靜態值不應更改。


當變量是靜態的時,同一類的所有對象中僅存在該變量的一個實例。因此,當您調用 時obj1.i = 25,您將更改類的所有i實例,包括您當前所在的實例。


如果我們單步執行代碼并看看它在做什么,這可能會更清楚:


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); 

}


查看完整回答
反對 回復 2024-01-05
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

int i是一個局部變量,僅存在于 的范圍內printvalue()(此方法應命名為printValue())。您將局部變量初始化i為 30。

obj1.i=25是Object 中的靜態 字段。當您實例化 時,您將創建一個靜態字段值為 10 的實例。然后將 的值更改為 25。iobj1objParentClass obj1= new ParentClass();ParentClassiobj1.i

這與局部變量無關int i


查看完整回答
反對 回復 2024-01-05
?
蠱毒傳說

TA貢獻1895條經驗 獲得超3個贊

您有不同的變量(在不同的范圍內),它們都被稱為i

  • 原始整數類型的靜態變量:static int i=15;

  • 原始整數類型的局部變量(僅在其所屬方法的范圍內可見printvalue()int i =30;

您可以從非靜態上下文訪問靜態變量,但不能從靜態上下文訪問實例變量。

在您的printvalue()方法中,您將 local var 設置i為值 30,然后為 static variable 設置一個新值 (25)?i。因為兩者共享相同的變量名,所以靜態變量i被它的本地對應變量“遮蔽”......這就是輸出為 30 而不是 25 的原因。

查看完整回答
反對 回復 2024-01-05
  • 3 回答
  • 0 關注
  • 268 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號