简体   繁体   English

为什么此类的每个对象对其成员都具有相同的值?

[英]Why does every object of this class have the same value for its members?

I'm writting an application which should be extremely simple but it keeps using the last set values for name and boxesSold for everything. 我正在编写一个应用程序,该应用程序应该非常简单,但它始终使用nameboxesSold的最后设置值来进行所有操作。 Here's a minimal example: 这是一个最小的示例:

public class BandBoosterDriver
{
  public static void main (String[] args)
  {
    BandBooster booster1 = new BandBooster("First");
    BandBooster booster2 = new BandBooster("Second");
    booster2.updateSales(2);

    System.out.println(booster1.toString());
    System.out.println(booster2.toString());
  }
}

and here is the problem class: 这是问题类别:

public class BandBooster
{
  private static String name;
  private static int boxesSold;

  public BandBooster(String booster)
  {
    name = booster;
    boxesSold = 0;
  }

  public static String getName()
  {
    return name;
  }

  public static void updateSales(int numBoxesSold)
  {
    boxesSold = boxesSold + numBoxesSold;
  }

  public String toString()
  {
    return (name + ":" + " " + boxesSold + " boxes");
  }
}

This produces 这产生

Second: 2 boxes
Second: 2 boxes

But I would expect 但是我希望

First: 0 boxes
Second: 2 boxes

How can I get it to work the way I expect it to? 如何使它按我期望的方式工作?

remove the static keyword. 删除static关键字。 static will indicate your program to use single memory address for this field , and avoid allocating dedicated memory for this field everytime you create an instance of BandBooster. static将指示您的程序对该字段使用单个内存地址,并且避免每次创建BandBooster实例时都为此字段分配专用内存。

因为它没有任何实例成员,所以只有静态成员。

Statically created variables are unique to the class and shared by all instances of it. 静态创建的变量对于该类是唯一的,并且由其所有实例共享。 What you are seeing is what's supposed to happen. 您所看到的是应该发生的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java中的每个对象都有自己的构造函数吗? - Does every Object in java have its own Constructor? 为什么在创建抽象类的引用类型对象和访问自己的成员时存在这种差异? - Why this difference in creating reference type object of an abstract class and accessing its own members? 我有2个相同值的String Buffer Class对象。 字符串equals()方法显示错误结果为什么? - I have 2 Same value object of String Buffer Class. String equals() method Showing False result Why? 如果hashmap的所有键具有相同的值,那么它如何工作? - How does a hashmap work if all its keys have the same value? Java是否为类成员提供动态变量? - Does Java have dynamic variables for class members? 为什么不变类Integer可以重置其值? - Why can the immutable class Integer have its value reset? 如何在不同的类中使用相同的对象及其值 - How to use same object with its value in different class 为什么我不能有一个与其包含类同名的两级深度内部类? - Why can't I have a two-level-deep inner class with the same name as its containing class? 您可以创建一个没有Object作为其基类的类结构 - Can you create a class structure that does not have Object as its base class 为什么对象引用的是父类的值而不是指派给它的类? - Why does the object refers to the value of the parent class instead of the class it is assigned to?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM