0

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?

Paul Hicks
  • 13,289
  • 5
  • 51
  • 78
DomBavetta
  • 13
  • 1
  • 1
  • 8
  • Read a tutorial on Object Oriented Programming with classes and objects. [This one](http://docs.oracle.com/javase/tutorial/java/javaOO/) for instance. – Sotirios Delimanolis May 30 '14 at 23:03
  • `private static String name;` means that there's only one name per class. Drop the `static`. – Paul Hicks May 30 '14 at 23:07
  • My searchfu is letting me down.. there must be a near-canonical question/answer we can mark this as a duplicate against. It's not this one.. [http://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class], that's not a dup. – Paul Hicks May 30 '14 at 23:09
  • Apologies for the major edit, but I couldn't find a duplicate, so I've updated this to be more generic, for future readers. – Paul Hicks May 30 '14 at 23:37

3 Answers3

1

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.

shaydel
  • 589
  • 4
  • 15
  • Thanks for the help, I guess I just mixed definitions for static. The program runs fine now! – DomBavetta May 30 '14 at 23:27
  • @user3067788 This answer solved your problem. It is appropriate to click the tick to the left to reward the answerer for their efforts. – Paul Hicks May 30 '14 at 23:38
0

Because it doesn't have any instance members, only static members.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
hd1
  • 33,938
  • 5
  • 80
  • 91