我书面方式应该是非常简单的应用程序,但它一直使用的最后一组值name
和boxesSold
一切。这是一个最小的示例:
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());
}
}
这是问题类别:
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");
}
}
这产生
Second: 2 boxes
Second: 2 boxes
但是我希望
First: 0 boxes
Second: 2 boxes
如何使它按我期望的方式工作?
删除static关键字。static将指示您的程序对该字段使用单个内存地址,并避免在每次创建BandBooster实例时都为此字段分配专用内存。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句