为什么 Main 方法中的静态变量值会发生变化?

我写了一个简单的程序,如下所示,这让我感到困惑:


    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?


慕沐林林
浏览 111回答 3
3回答

慕莱坞森

我的问题是类级别 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); }

拉莫斯之舞

int i是一个局部变量,仅存在于 的范围内printvalue()(此方法应命名为printValue())。您将局部变量初始化i为 30。obj1.i=25是Object 中的静态 字段。当您实例化 时,您将创建一个静态字段值为 10 的实例。然后将 的值更改为 25。iobj1objParentClass obj1= new ParentClass();ParentClassiobj1.i这与局部变量无关int i。

蛊毒传说

您有不同的变量(在不同的范围内),它们都被称为i:原始整数类型的静态变量:static int i=15;原始整数类型的局部变量(仅在其所属方法的范围内可见printvalue():int i =30;您可以从非静态上下文访问静态变量,但不能从静态上下文访问实例变量。在您的printvalue()方法中,您将 local var 设置i为值 30,然后为 static variable 设置一个新值 (25) i。因为两者共享相同的变量名,所以静态变量i被它的本地对应变量“遮蔽”......这就是输出为 30 而不是 25 的原因。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java