为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 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 关注
  • 108 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信