简体   繁体   中英

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. 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 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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM