Java 中的静态变量/新学习者

问题描述 投票:0回答:1
package drinks;
public class Dairy {
  public static Dairy dairyclssobj = null;
  private Dairy(){}

public static Dairy getDairy() {
    if (dairyclssobj==null) {
         dairyclssobj = new Dairy();
         return dairyclssobj;
    }
    return dairyclssobj;    
}

static String brandname = "  oompaa..lumpaa..Drinks";

public static void main(String[] args) {

    System.out.println(brandname);
}
}
class Chocolateee {
  public static void main(String[] args) {
    
     Dairy.brandname = "..Yum Drinks";
     System.out.println("The brand name now is " + Dairy.brandname);
   }    
}
class Chocolate1  {
  static String bnameString = Dairy.brandname;
  public static void main(String[] args) {
     System.out.println("The brand name now is " + bnameString);
  }
}

我是 Java 新手,试图理解

static
关键字。

这是我在 Eclipse 中创建的项目。包装是乳制品,并且 问题是,即使我在 Chocolateee 类中更改了它,Dairy 类中的静态字符串品牌名称值对于 Chocolate1 类也没有更改。它应该是“Yum Drinks”,但输出仍然是“oompaa.lumpaa.Drinks”。即使我将整个类变成一个单例,它仍然会产生相同的输出。

执行顺序:首先我执行了Dairy、2nd Chocolateee和3rd Chocolate1。

Dairy 的输出为“oompaa.lumpaa.Drinks”,Chocolatee 的输出为“Yum Drinks”,Chocolate1 的输出为“oompaa.lumpaa.Drinks”。

我上课的方式不对吗?不是在对象之间共享静态变量,并且如果一个类更改了它,则所有值都会更改...为什么我会得到此输出?

java object static core
1个回答
0
投票

实际上你的程序中有3个端点不能一起执行。事实上,这是 3 个独立的程序。如果你想改变

Dairy.brandname
你可以尝试这样的事情:

package drinks;

public class Dairy {
      public static String brandname = "  oompaa..lumpaa..Drinks";
}

public class Chocolateee {
    public static void changeDairyBrandname() {
        Dairy.brandname = "..Yum Drinks";
    }    
}

public class UnderstandStaticKeyword {

    public static void main(String[] args) {
        System.out.println("The brand name now is " + Dairy.brandname);
        Chocolateee.changeDairyBrandname()
        System.out.println("The brand name now is " + Dairy.brandname);
    }
}

为了更好地理解,您可以阅读这篇文章

© www.soinside.com 2019 - 2024. All rights reserved.